Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does if [ $? -eq 0 ] mean for shell scripts? [duplicate]

Tags:

bash

shell

There is this line in a shell script i have seen:

grep -e ERROR ${LOG_DIR_PATH}/${LOG_NAME}  > /dev/null if [ $? -eq 0 ]  
like image 560
Oh Chin Boon Avatar asked Aug 18 '11 03:08

Oh Chin Boon


People also ask

What is if $? 0 in shell script?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.

What is role of $0 $? And $# in shell scripting?

If you execute ./script.sh , $0 will give output ./script.sh but if you execute it with bash script.sh it will give output script.sh . Show activity on this post. They are called the Positional Parameters.

What does $? Mean shell script?

Show activity on this post. echo $? - Gives the EXIT STATUS of the most recently executed command . This EXIT STATUS would most probably be a number with ZERO implying Success and any NON-ZERO value indicating Failure.

What will be the result of Echo $$ $? $! $0 command?

As explained in this comment on that answer you link to, echo $0 simply shows you the name of the currently running process: $0 is the name of the running process. If you use it inside of a shell then it will return the name of the shell. If you use it inside of a script, it will be the name of the script.


1 Answers

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded.

The grep manpage states:

The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2. (Note: POSIX error handling code should check for '2' or greater.)

So in this case it's checking whether any ERROR lines were found.

like image 96
Wyzard Avatar answered Oct 01 '22 04:10

Wyzard