How to Extract Command Exit Status into a Variable

bashcommand lineexit-statusgrepshell

I started learning Bash a couple of days ago.

I'm trying to obtain an exit status of grep expression into a variable like this:

check=grep -ci 'text' file.sh

and the output that I got is

No command '-ic' found

Should I do it with a pipe command?

Best Answer

Your command,

check=grep -ci 'text' file.sh

will be interpreted by the shell as "run the command -ci with the arguments text and file.sh, and set the variable check to the value grep in its environment".


The shell stores the exit value of most recently executed command in the variable ?. You can assign its value to one of your own variables like this:

grep -i 'PATTERN' file
check=$?

If you want to act on this value, you may either use your check variable:

if [ "$check" -eq 0 ]; then
    # do things for success
else
    # do other things for failure
fi

or you could skip using a separate variable and having to inspect $? all together:

if grep -q -i 'pattern' file; then
  # do things (pattern was found)
else
  # do other things (pattern was not found)
fi

(note the -q, it instructs grep to not output anything and to exit as soon as something matches; we aren't really interested in what matches here)

Or, if you just want to "do things" when the pattern is not found:

if ! grep -q -i 'pattern' file; then
  # do things (pattern was not found)
fi

Saving $? into another variable is only ever needed if you need to use it later, when the value in $? has been overwritten, as in

mkdir "$dir"
err=$?

if [ "$err" -ne 0 ] && [ ! -d "$dir" ]; then
    printf 'Error creating %s (error code %d)\n' "$dir" "$err" >&2
    exit "$err"
fi

In the above code snippet, $? will be overwritten by the result of the [ "$err" -ne 0 ] && [ ! -d "$dir" ] test. Saving it here is really only necessary if we need to display it and use it with exit.