【问题标题】:Conditionals not being tested properly未正确测试条件
【发布时间】:2018-09-12 05:54:36
【问题描述】:

我的 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

这可以在输出文件中找到:

.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

我查看了多个关于如何编写 bash 条件的指南,但没有发现任何问题。 $1 变量可用,但在 if 语句中被忽略

【问题讨论】:

  • echo "$1" 显示什么?顺便说一句,为什么你将它标记为 bash 而你的脚本在 shebang 行中有#!/bin/sh
  • 是的,这就是问题所在,以为我在使用 sh 时使用的是 bash

标签: bash syntax


【解决方案1】:

您在[ ] 中使用== 而不是=,但这是一种贬义。最近的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

解决方法:切换到=

$ if [ foo = foo ]; then echo "The strings match"; else echo "The strings do *not* match"; fi
The strings match

如果你打算使用/bin/sh 而不是/bin/bash,你真的需要提防bashisms。 the Ubuntu wiki 中有一个很好的页面。要么这样,要么切换到 /bin/bash。

附:如果你打算使用 bash 扩展,我建议使用 [[ ]] 而不是 [ ] 作为条件 - 它修复了 [ ] 的大部分语法怪异,并添加了一些有用的新功能,如模式和正则表达式匹配。

【讨论】:

  • 谢谢!解决了。​​
【解决方案2】:

很可能,我认为您在第 4 行弄错了重定向输出。

必须是:

echo "we are suspending at $(date)..." >> /home/albin/stuff/suspend_test

而不是

echo "we are suspending at $(date)..." > /home/albin/stuff/suspend_test

另外,我认为 1 美元既不等于 'pre' 也不等于 'post'。通过查看您发布的输出,我无法理解这些字符串 "tis""ons" 的来源。

【讨论】:

  • "tis" 和 "ons" 是瑞典语中 "Tuesday" 和 "Wednesday" 的缩写
【解决方案3】:

这个脚本的调用者可能会向您传递除 post 或 pre 之外的其他参数。 将日志写入更改为使用 >> 而不是 >(以防止一直覆盖日志)并尝试在第一行添加 echo "${1}" >> log,然后您可以查看脚本中的参数

【讨论】:

    猜你喜欢
    • 2017-01-26
    • 2015-04-04
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多