Bash Scripting – Grep Command Not Returning Expected Results for Testing

bashshelltest

I am attempting to do a comparison before I append conditions to a profile.d file

A grep -F 'TMOUT' /etc/profile.d/sh.local shows me exactly what I expect however the test is always showing true. In all of these examples I've already appended the information I want to sh.local but I don't want to do it again if it is present.

[ ! `grep -Fq 'TMOUT' /etc/profile.d/sh.local` ] && echo $?
0
[ ! `grep -Fq 'NOT_PRESENT' /etc/profile.d/sh.local` ] && echo $?
0

Although this is for an .ebextension command the tests are failing before I even try to deploy, I imagine the final result should look like this but I'm obviously wrong about something. I've tried using $(grep) vs `grep`. Also ==1 vs !

  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

And for the record this is Amazon Linux 2 and the following commands spit out the following

grep -F 'TMOUT' /etc/profile.d/sh.local
TMOUT=300
readonly TMOUT
export TMOUT

grep -F 'NOT_PRESENT' /etc/profile.d/sh.local

Best Answer

In

[ ! `grep -Fq 'TMOUT' /etc/profile.d/sh.local` ] && echo $?
0
[ ! `grep -Fq 'NOT_PRESENT' /etc/profile.d/sh.local` ] && echo $?
0

the backticks around the grep command constitute a command substitution, returning the command's standard output. Since you used -q, standard output is always empty so regardless of what string you grep for, your [ ! ... ] tests both become

[ ! ]

This is the "one argument form" of the test construct, and tests the non-emptiness of the one-character string ! - which is always true.

To test the exit status of the grep commands you may use:

grep -Fq 'TMOUT' /etc/profile.d/sh.local && echo $?

See also


Likewise,

[ $(grep -Fxq 'TMOUT' /etc/profile.d/sh.local) ==1 ]

becomes

[ ==1 ]

which tests the non-emptiness of string ==1; you probably intended to write == 1 which would at least have errored out with message [: ==: unary operator expected - see

Related Question