[Shell Script](EN) Check command substitution's result exists or not in conditional statement
Check command substitution’s result exists or not in conditional statement
Environment and Prerequisite
- Linux
- Bash shell(/bin/bash)
Situatiaton and Method
Situatiaton
- Below is situatiaton that conditional statement is needed to check command substitution’s result exists or not
command substitution
is allowing the output of a command to replace the command itself by using subshell.
#!/bin/sh
result=$(ls -al | grep sample)
...
Method
- Use below conditional statements.
- Handle different way by using
-z
option. - (Method 1) You can check it by only adding variable in conditional statement. If its length is 0 or it is not set, then it is considered as false.
- (Method 2) Use
-z
option. If variable next to-z
is not set or length is 0, then it is considered as true.
#!/bin/sh
result=$(ls -al | grep sample)
# Return true if its length is not zero.
if [ "${result}" ]
then
echo "result is not empty"
else
echo "result is empty"
fi
# Checks if the given string operand size is zero; if it is zero length, then it returns true.
if [ -z "${result}" ]
then
echo "result is empty"
else
echo "result is not empty"
fi
Example
- Add specific string if it not exists in file
- Consider file exists
$ cat test.txt
String
$ vi test.sh
#!/bin/sh
set -e
set +e
result=$(cat test.txt | grep "test string")
set -e
if [ -z "${result}" ]
then
echo "test string" >> test.txt
fi
$ chmod +x test.sh
$ ./test.sh
$ cat test.txt
String
test string
etc
- In
grep
command, normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. So if you useset -e
option, then you need to unset that option before using it. - Reference: https://www.gnu.org/software/grep/manual/grep.html#Exit-Status
...
set +e
result=$(ls -al | grep sample)
set -e
...
Reference
- https://www.gnu.org/software/bash/manual/html_node/Command-Substitution.html
- https://en.wikipedia.org/wiki/Command_substitution
- https://www.tutorialspoint.com/unix/unix-string-operators.htm
- https://stackoverflow.com/questions/12137431/test-if-a-command-outputs-an-empty-string
- https://www.cyberciti.biz/faq/unix-linux-bash-script-check-if-variable-is-empty/
- https://www.gnu.org/software/grep/manual/grep.html#Exit-Status