orschiro
orschiro

Reputation: 21725

Writing a hibernation timer using systemctl hibernate

I wanted to write a hibernation timer function using systemctl hibernate and root privileges.

This is my function:

hibernate-timer() {
  sudo bash -c 'echo "System is going to hibernate in $1 minute(s)..." 
  sleep $1m
  systemctl hibernate'
}

When running for instance hibernate-timer 50, I would expect the system to hibernate after 50 minutes. However, I get the following error message: sleep: invalid time interval ‘m’.

Can anyone tell me how I can write a hibernation timer using root privileges?

Upvotes: 3

Views: 901

Answers (1)

janos
janos

Reputation: 124646

You forgot to pass the parameter to bash -c after the single quotes:

hibernate-timer() {
  sudo bash -c 'echo "System is going to hibernate in $1 minute(s)..." 
  sleep $1m
  systemctl hibernate' -- $1
}

Notice the -- $1 I added near the end. Without this, the command in bash -c is not getting any command line arguments, so the value of $1 inside the command is empty, so instead of sleep 50m the command becomes sleep m which won't work.

From the man page:

   --        A  --  signals the end of options and disables further option
             processing.  Any arguments after the -- are treated as  file‐
             names and arguments.

This is how the -- $1 there gets passed in as argument for the command within bash -c '...'

Upvotes: 3

Related Questions