Skip to content

Instantly share code, notes, and snippets.

@caffeinetiger
Last active April 18, 2022 16:58
Show Gist options
  • Save caffeinetiger/02ef4f271c1f69d9f29aea1a21cf50fe to your computer and use it in GitHub Desktop.
Save caffeinetiger/02ef4f271c1f69d9f29aea1a21cf50fe to your computer and use it in GitHub Desktop.
## References: - [Checking if a Linux Environment Variable Is Set or Not](https://www.baeldung.com/linux/environment-variable-check-if-set) - [Bash Cheatsheet: check if environment variables are set or file/symlinks exists + more](https://codewithhug

Follow bash best-practices

These examples were compiled from Best Practices for Writing Bash Scripts and Use the Unofficial Bash Strict Mode (Unless You Looove Debugging).

Another resource of note: Bash 3 Boilerplate.

As a single snippet, start your bash script with:

set -euo pipefail

set -e or -o errexit - exit when a command fails Add the following at the start of your script. It will make the script exit when a command fails.

set -e

set -u or -o nounset - exit when trying to use undefined variable Add the following at the start of your script. It will make the script exit when attempting to use an undefined variable.

set -u

set -o pipefail - return the exit code of piped commands that error Add the following at the start of your script.

It will return the exit code of the last command to exit with a non-zero status code (ie. error).

set -o pipefail

Debug with set -x or -o xtrace Add the following to print out each commans befoee it’s executed.

set -x

Check if a file exists in bash

if [ ! -f ./pdfgen/pdfgen ]; then
    echo "Building pdfgen binary"
    npm run --prefix pdfgen build:linux
else
    echo "Pdfgen binary already exists, skipping build"
fi

Check if a (symbolic) link exists in bash

if [ ! -L /usr/local/bin/heroku ];
then
    wget https://cli-assets.heroku.com/branches/stable/heroku-linux-amd64.tar.gz
    sudo mkdir -p /usr/local/lib /usr/local/bin
    sudo tar -xvzf heroku-linux-amd64.tar.gz -C /usr/local/lib
    sudo ln -s /usr/local/lib/heroku/bin/heroku /usr/local/bin/heroku
fi

Check if an environment variable is set in bash

# long
if [[ -z "${CIRCLE_BRANCH}"] ]; then
    npm run redis-cli flushall
fi
 
npm run sync

# one-liner
[-z "${CIRCLE_BRANCH}"] && npm run redis-cli flushall; npm run sync

Switch over an environment variable in bash

case $CIRCLE_BRANCH in
    "develop")
        export ENVIRONMENT="dev"
        export HEROKU_APP=dev-app
        ;;
    "staging")
        export ENVIRONMENT="staging"
        export HEROKU_APP=staging-app
        ;;
    "production")
        export ENVIRONMENT="production"
        export HEROKU_APP=production-app
        ;;
esac

Prompt the user in bash

read -p "Are you sure you want to merge 'develop' into 'staging'? (y/N)" -n 1 -r
echo # we like having a new line

if [[ $REPLY =~ ^[Yy]$ ]]
then
  git merge develop --ff-only
  git push
fi

A final bit of advice, if it’s more than a couple of lines, try to use something like JavaScript, or Python to write your script.

I’ve got some resources to do that in modern JavaScript/Node:

Inject .env into your bash session/environment

We’ve got .env files laying around, Docker Compose deals with this for use usually but say we want to get something running outside of Docker (and without using something like dotenv).

Here’s the snippet for a *NIX shell:

export $(cat .env | xargs)

Checking if a Linux Environment Variable Is Set or Not

Taken from Checking if a Linux Environment Variable Is Set or Not. All credit goes to Narendra Kangralkar

1. Overview

As Linux users, we frequently work with shell scripts. One of the common requirements in scripts is to test if a particular environment variable is set or not. This helps in handling various error conditions.

In this tutorial, we’ll see the various example to check if a particular environment variable is set or not.

2. Using the if Conditional Expression

We can use the if conditional expression to check if a value is assigned to a variable or not:

$ VAR= 
$ if [ x"${VAR}" == "x" ]; then 
     echo "Value is not assigned to a variable"
  else
     echo "Value is assigned to a variable"
  fi
Value is not assigned to a variable

Let’s assign a value to a variable and verify the result:

$ VAR="sample-value"
$ if [ x"${VAR}" == "x" ]; then
     echo "Value is not assigned to a variable"
  else 
     echo "Value is assigned to a variable"
  fi
Value is assigned to a variable

3. Using the Double Square Brackets

Another way to check if a variable is set or not is by using a double square bracket:

$ VAR=
$ [[ x"${VAR}" == "x" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is not assigned to a variable

Let’s verify the output by assigning a value to a variable:

$ VAR="sample-value"
$ [[ x"${VAR}" == "x" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is assigned to a variable

Note that this method works only with Bash, Z Shell (zsh), and Korn Shell (ksh).

4. Using the Parameter Expression

We can use bash built-in parameter expressions to check if a variable is set or not:

$ VAR=
$ [[ ${VAR:-"unset"} == "unset" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is not assigned to a variable

Let’s set the value of a variable and check whether it works:

$ VAR="sample-value"
$ [[ ${VAR:-"unset"} == "unset" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is assigned to a variable

5. Using the -z Conditional Expression

In bash, there is a -z conditional expression that returns true if the length of a string is zero. We can use this property to check if a variable is set or not:

$ VAR=
$ [[ -z "${VAR}" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is not assigned to a variable

Let’s try it out:

$ VAR="sample-value"
$ [[ -z "${VAR}" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is assigned to a variable

6. Using the -n Conditional Expression

Similarly, there is -n conditional expression that returns true if the length of a string is non-zero. We can use this property to check if a variable is set or not:

$ VAR=
$ [[ ! -n "${VAR}" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is not assigned to a variable

Let’s update the value of a variable and confirm the result:

$ VAR="sample-value"
$ [[ ! -n "${VAR}" ]] && echo "Value is not assigned to a variable" || echo "Value is assigned to a variable"
Value is assigned to a variable

7. Conclusion

In this tutorial, we discussed various practical examples to check if a variable is set or not. First, we discussed if conditional expression. Then we discussed parameter expression, and finally, we discussed built-in conditional expressions of the bash. We can use these commands in day-to-day life to make shell scripts more robust.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment