简体   繁体   中英

Why bash script using if and grep works one every other call?

root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
12
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
12
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
root@xxx:/#  [ "`date | grep 20 | echo $?`" -gt "0" ] && echo 12
12

It should echo 12 on every line, but do so only on odd lines. Why? How to fix?

You are assuming that foo | echo $? foo | echo $? will show the exit status of foo . This is not the case. Instead, it shows the exit status of the previous command or pipeline:

$ bash -c 'exit 42'
$ true | echo $?
42

Your command therefore flip-flops like this one:

$ [ $? = 1 ] && echo "Boop"
$ [ $? = 1 ] && echo "Boop"
Boop
$ [ $? = 1 ] && echo "Boop"
$ [ $? = 1 ] && echo "Boop"
Boop

What you intended was to suppress grep output (here done with -q ), and then add a second command (after a ; ) that can write out the value:

# Check for success when running a command and writing out
# the exit status and capturing it and comparing it to success
[ "`date | grep -q 20; echo $?`" -gt "0" ] && echo 12

However, you can drop all the redundancies and just do:

# Check for success when running a command
date | grep -q 20 && echo 12

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM