![如果语句未按预期执行,我是否错误地设置了变量?](https://linux22.com/image/1487503/%E5%A6%82%E6%9E%9C%E8%AF%AD%E5%8F%A5%E6%9C%AA%E6%8C%89%E9%A2%84%E6%9C%9F%E6%89%A7%E8%A1%8C%EF%BC%8C%E6%88%91%E6%98%AF%E5%90%A6%E9%94%99%E8%AF%AF%E5%9C%B0%E8%AE%BE%E7%BD%AE%E4%BA%86%E5%8F%98%E9%87%8F%EF%BC%9F.png)
我正在尝试创建一个命令,使我能够检查网站上是否有特定的单词。我在行尾使用了 \ 来换行到下一行(不确定我在这里是否使用正确),这些字符不在我的脚本中。
check=$(lynx -source $1 | grep -i $2)
if [[ $check == *"$2"* ]]
then
/usr/local/bin/sendemail -o tls=yes -f ***@gmail.com -t\
[email protected] -s smtp.gmail.com:587 -xu ***@gmail.com -xp *** -u\
$1 -m "contains the word " $2 ".";
else
/usr/local/bin/sendemail -o tls=yes -f ***@gmail.com -t\
[email protected] -s smtp.gmail.com:587 -xu ***@gmail.com -xp *** -u\
$1 -m "does not contain the word " $2 ".";
fi
答案1
您正在使用grep
不区分大小写的方式检查输出,然后使用区分大小写的 glob 模式检查 grep 的输出。
这样做:
if lynx -source "$1" | grep -qi "$2"; then
msg="contains the word '$2'."
else
msg="does not contain the word '$2'."
fi
/usr/local/bin/sendemail -o tls=yes -f ***@gmail.com -t [email protected] -s smtp.gmail.com:587 -xu ***@gmail.com -xp *** -u "$1" -m "$msg"
答案2
如果语句没有按预期进行评估。
使用以下方法检查脚本壳牌检测(在您的 shell 脚本中发现错误。)给出了以下建议:
$ shellcheck myscript
Line 1:
check=$(lynx -source $1 | grep -i $2)
^-- SC2086: Double quote to prevent globbing and word splitting.
^-- SC2086: Double quote to prevent globbing and word splitting.
Line 5:
/usr/local/bin/sendemail -o tls=yes -f ***@gmail.com -t\
^-- SC2035: Use ./*glob* or -- *glob* so names with dashes won't become options.
Line 6:
[email protected] -s smtp.gmail.com:587 -xu ***@gmail.com -xp *** -u\
^-- SC2035: Use ./*glob* or -- *glob* so names with dashes won't become options.
^-- SC2035: Use ./*glob* or -- *glob* so names with dashes won't become options.
Line 7:
$1 -m "contains the word " $2 ".";
^-- SC2086: Double quote to prevent globbing and word splitting.
^-- SC2086: Double quote to prevent globbing and word splitting.
Line 10:
/usr/local/bin/sendemail -o tls=yes -f ***@gmail.com -t\
^-- SC2035: Use ./*glob* or -- *glob* so names with dashes won't become options.
Line 11:
[email protected] -s smtp.gmail.com:587 -xu ***@gmail.com -xp *** -u\
^-- SC2035: Use ./*glob* or -- *glob* so names with dashes won't become options.
^-- SC2035: Use ./*glob* or -- *glob* so names with dashes won't become options.
Line 12:
$1 -m "does not contain the word " $2 ".";
^-- SC2086: Double quote to prevent globbing and word splitting.
^-- SC2086: Double quote to prevent globbing and word splitting.
$
请参阅以下链接以了解建议的解释: