I am trying to use grep as a variable and a function in a bash shell script. I get the desired output when grep is used as an variable. I do not get the desired output when grep is used as an function.
The script used for grep as a variable is as below:
#! /bin/bash grep=$(grep -ico "mmshutdown: Finished" mmshutdown-output.txt) #grep() #{ # grep -ico "mmshutdown: Finished" mmshutdown-output.txt #} status() { echo $? } if [[ "grep" -gt "0" ]]; then echo echo "exit code of search mmshutdown: Finished is $(status)" echo echo "FILE SYSTEM UNMOUNTED SUCESSFULLY" sleep 3 else echo "exit code of search mmshutdown: Finished is $(status)" echo "check output log file mmshutdown.txt" sleep 3 fi
the out put when we run the script is
[root@ad ~]# ./grep-variable.sh exit code of search mmshutdown: Finished is 0 FILE SYSTEM UNMOUNTED SUCESSFULLY
The script used for grep in function is as below:
#! /bin/bash #grep=$(grep -ico "mmshutdown: Finished" mmshutdown-output.txt) grep() { grep -ico "mmshutdown: Finished" mmshutdown-output.txt } status() { echo $? } if [[ "grep" -gt "0" ]]; then echo echo "exit code of search mmshutdown: Finished is $(status)" echo echo "FILE SYSTEM UNMOUNTED SUCESSFULLY" sleep 3 else echo "exit code of search mmshutdown: Finished is $(status)" echo "check output log file mmshutdown.txt" sleep 3 fi
the out put when we run the script is
[root@ad ~]# ./grep-function.sh exit code of search mmshutdown: Finished is 1 check output log file mmshutdown.txt
Could someone point out what has gone wrong here? Why is grep when used as function not providing desired output?
Advertisement
Answer
Your both programs are comparing “grep” with “0” not the output of the grep command. Also -c option returns the number of lines matched.
Check the following code it works with grep as function. But as grep is as a function you will need to call original grep i.e. command with complete path else it will go in an infinite loop. Send output to /dev/null and process on command execution status.
#! /bin/bash set -x #grep=$(grep -ico "mmshutdown: Finished" mmshutdown-output.txt) grep() { return $(/bin/grep -ico "mmshutdown: Finished" mmshutdown-output.txt > /dev/null) } status() { echo $? } if grep; then echo echo "exit code of search mmshutdown: Finished is $(status)" echo echo "FILE SYSTEM UNMOUNTED SUCESSFULLY" sleep 3 else echo "exit code of search mmshutdown: Finished is $(status)" echo "check output log file mmshutdown.txt" sleep 3 fi