如果语句未按预期执行,我是否错误地设置了变量?

如果语句未按预期执行,我是否错误地设置了变量?

我正在尝试创建一个命令,使我能够检查网站上是否有特定的单词。我在行尾使用了 \ 来换行到下一行(不确定我在这里是否使用正确),这些字符不在我的脚本中。

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.

$ 

请参阅以下链接以了解建议的解释:

相关内容