Understanding the :? Parameter Expansion in Bash

ยท

1 min read

When writing shell scripts, ensuring that certain variables are set and not empty is crucial. One handy feature in Bash for this purpose is the :? parameter expansion.

The :? syntax is a form of parameter expansion in Bash that allows you to check if a variable is set and non-empty. If the variable is not set or is empty, the shell will display an error message and exit the script. This feature helps in writing robust scripts by enforcing that essential variables are always defined.

Let us look at an example of how to use it as below:

: "${S3_BUCKET:?You must set S3_BUCKET to the target bucket name}"
aws s3 cp myfile.txt "s3://$S3_BUCKET/myfile.txt"

Imagine you have a script that uploads files to an S3 bucket, and it requires an environment variable S3_BUCKET to be set. By using :?, you can enforce that this variable is defined before proceeding. If S3_BUCKET is not set, the script will exit with a clear message You must set S3_BUCKET to the target bucket name, preventing potential errors in the upload process.

Note the : preceding the variable expansion within the quotes is a shell built-in command that does nothing and returns true. It's often used as a placeholder for commands.

Happy Bash scripting!

ย