Grep 命令未返回预期的测试结果

Mik*_*keG 4 shell bash test

我试图在将条件附加到 profile.d 文件之前进行比较

Agrep -F 'TMOUT' /etc/profile.d/sh.local准确地显示了我的期望,但是测试总是显示正确。在所有这些示例中,我已经将我想要的信息附加到 sh.local 但如果它存在我不想再做一次。

[ ! `grep -Fq 'TMOUT' /etc/profile.d/sh.local` ] && echo $?
0
[ ! `grep -Fq 'NOT_PRESENT' /etc/profile.d/sh.local` ] && echo $?
0
Run Code Online (Sandbox Code Playgroud)

尽管这是针对 .ebextension 命令的测试在我什至尝试部署之前都失败了,但我想最终结果应该是这样的,但我显然错了。我试过使用 $(grep) 和 `grep`。还有 ==1 对 !

[ ! `grep -Fq 'TMOUT' /etc/profile.d/sh.local` ] && echo $?
0
[ ! `grep -Fq 'NOT_PRESENT' /etc/profile.d/sh.local` ] && echo $?
0
Run Code Online (Sandbox Code Playgroud)

作为记录,这是 Amazon Linux 2 和以下命令吐出以下内容

  01_hard_5.4.5_shell_timeout:
    test: "[ $(grep -Fxq 'TMOUT' /etc/profile.d/sh.local) ==1 ]"
    command: |
      printf '\nTMOUT=300\nreadonly TMOUT\nexport TMOUT\n' | sudo tee -a /etc/profile.d/sh.local >/dev/null

Run Code Online (Sandbox Code Playgroud)

ste*_*ver 13

[ ! `grep -Fq 'TMOUT' /etc/profile.d/sh.local` ] && echo $?
0
[ ! `grep -Fq 'NOT_PRESENT' /etc/profile.d/sh.local` ] && echo $?
0
Run Code Online (Sandbox Code Playgroud)

grep 命令周围的反引号构成命令替换,返回命令的标准输出。自从您使用以来-q,标准输出始终为空,因此无论您搜索什么字符串,您的[ ! ... ]测试都将变为

[ ! ]
Run Code Online (Sandbox Code Playgroud)

这是测试构造的“单一参数形式”,并测试单字符串的非空性!- 这总是正确的。

要测试grep 命令的退出状态,您可以使用:

grep -Fq 'TMOUT' /etc/profile.d/sh.local && echo $?
Run Code Online (Sandbox Code Playgroud)

也可以看看


同样地,

[ $(grep -Fxq 'TMOUT' /etc/profile.d/sh.local) ==1 ]
Run Code Online (Sandbox Code Playgroud)

变成

[ ==1 ]
Run Code Online (Sandbox Code Playgroud)

测试 string 的非空性==1;您可能打算编写== 1至少会因消息而出错的内容[: ==: unary operator expected- 请参阅