How does one extract a command's exit status into a variable?

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.


You've told bash to set the variable check=grep in the environment it passes to the command

-ci 'text' file.sh

but ci does not exist.

I believe you meant to enclose that command in back-ticks, or in parentheses preceded by a dollar sign, either of which would assign the count of how many lines 'text' was found on (case insensitively) in the file:

check=`grep -ci 'text' file.sh`

check=$(grep -ci 'text' file.sh)

Now $check should be 0 if no matches, or positive if there were any matches.


Your question is unclear but based on the code you’ve submitted, it looks like you want the variable check to store the exit status of the grep command. The way to do this is to run

grep -ci 'text' file.sh
check=$?

When running a command from a shell, its exit status is made available through the special shell parameter, $?.

This is documented by POSIX (the standard for Unix-like operating systems) in its specification for the shell and the Bash implementation is documented under Special Parameters.

Since you’re a new learner, I’d strongly recommend that you start with a good book and/or online tutorial to get the basics. Recommendations of external resources are discouraged on Stack Exchange sites but I’d suggest Lhunath and GreyCat’s Bash Guide.