使用systemctl hibernate编写休眠计时器

时间:2013-12-01 08:05:22

标签: bash sleep

我想使用systemctl hibernate和root权限编写一个休眠计时器功能。

这是我的功能:

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

当运行hibernate-timer 50时,我希望系统在50分钟后休眠。但是,我收到以下错误消息:sleep: invalid time interval ‘m’

有谁能告诉我如何使用root权限编写休眠计时器?

1 个答案:

答案 0 :(得分:1)

您忘记在单引号后将参数传递给bash -c

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

请注意我在最后添加的-- $1。如果没有这个,bash -c中的命令没有获取任何命令行参数,因此命令中$1的值为空,因此命令变为sleep 50m而不是sleep m哪个不行。

从手册页:

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

这就是-- $1作为bash -c '...'

中命令的参数传入的方式