[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

...
set +e
result=$(ls -al | grep sample)
set -e
...


Reference