每次我的Ubuntu机器醒来并进入睡眠状态时,我都会运行这个脚本.
#!/bin/sh
if [ "${1}" == "pre" ]; then
# Do the thing you want before suspend here, e.g.:
echo "we are suspending at $(date)..." > /home/albin/stuff/suspend_test
elif [ "${1}" == "post" ]; then
# Do the thing you want after resume here, e.g.:
echo "...and we are back from $(date)" >> /home/albin/stuff/suspend_test
else
echo ".2..neither pre or post . $1 . $(date)" >> /home/albin/stuff/suspend_test
fi
Run Code Online (Sandbox Code Playgroud)
这可以在输出文件中找到:
.2..neither pre or post . pre . tis 11 sep 2018 20:44:42 CEST
.2..neither pre or post . post . tis 11 sep 2018 20:45:06 CEST
.2..neither pre or post . pre . tis 11 sep 2018 22:12:52 CEST
.2..neither pre or post . post . ons 12 sep 2018 06:55:21 CEST
.2..neither pre or post . pre . ons 12 sep 2018 06:55:22 CEST
.2..neither pre or post . post . ons 12 sep 2018 06:55:43 CEST
.2..neither pre or post . pre . ons 12 sep 2018 07:13:28 CEST
.2..neither pre or post . post . ons 12 sep 2018 07:14:00 CEST
Run Code Online (Sandbox Code Playgroud)
我已经检查了多个指南,了解如何编写bash条件而不会发现任何问题.$ 1变量可用但在if语句中被忽略
你使用的==不是=内部[ ],而是一种基础.最新版本的Ubuntu使用dash作为/ bin/sh,它不支持==; 它得到一个错误,这被解释为测试失败:
$ if [ foo == foo ]; then echo "The strings match"; else echo "The strings do *not* match"; fi
dash: 1: [: foo: unexpected operator
The strings do *not* match
Run Code Online (Sandbox Code Playgroud)
解决方案:切换到 =
$ if [ foo = foo ]; then echo "The strings match"; else echo "The strings do *not* match"; fi
The strings match
Run Code Online (Sandbox Code Playgroud)
如果你要使用/bin/sh而不是/bin/bash,你真的需要注意基本原理.在Ubuntu wiki上有一个很好的页面.要么是这样,要么切换到/ bin/bash.
Ps如果您打算使用bash扩展,我建议使用[[ ]]而不是[ ]条件 - 它修复了大部分语法上的奇怪之处[ ],并添加了一些有用的新功能,如模式和正则表达式匹配.