Linting Bash Scripts with ShellCheck: Quoting and Safe Expansions

Shell script passing through a quality check with warnings for unsafe expansions and missing quotation boundaries

What You’ll Learn

Shell scripts can appear to work while still containing quoting errors, unsafe expansions, or commands that behave differently on another system. ShellCheck is a static analysis tool that examines shell scripts without running them and points out many of these problems.

  • Install and run ShellCheck on a Bash script.
  • Understand why quoting variables matters.
  • Recognize unsafe word splitting and expansion warnings.
  • Use ShellCheck before deploying automation scripts.
Ad

The Concept

Linting means checking source code for likely mistakes and quality problems. A linter does not usually execute your program. Instead, it looks at the code and reports patterns that are commonly incorrect or unsafe.

ShellCheck is a linter designed for shell scripts, including Bash scripts. It can identify problems such as:

  • Using an unquoted variable that may contain spaces.
  • Expanding a command result in a way that causes unexpected word splitting.
  • Using a test expression that behaves differently from what you intended.
  • Relying on shell features that are not portable to another shell.

ShellCheck does not prove that a script is correct. It cannot understand every business rule or predict every deployment environment. However, it is an inexpensive check to run before committing or deploying a script.

Installing ShellCheck

On Debian or Ubuntu, install ShellCheck with:

sudo apt update
sudo apt install shellcheck

On macOS with Homebrew, use:

brew install shellcheck

After installation, check that the command is available:

shellcheck --version

To lint a script, pass its filename to shellcheck:

shellcheck deploy_report.sh

A successful check produces no warning messages and exits successfully. If ShellCheck finds a problem, it reports a line number, a warning code such as SC2086, and an explanation.

Basic Example

Imagine a deployment script that receives an environment name and a configuration-file path as command-line arguments. This version runs, but it does not safely quote the environment variable in its test:

#!/usr/bin/env bash

environment=$1
config_file=$2

if [ $environment = production ]; then
    echo "Deploying $config_file to $environment"
fi

Save the file as deploy_report.sh, make it executable, and run ShellCheck:

chmod +x deploy_report.sh
shellcheck deploy_report.sh

Expected Output

ShellCheck reports a warning about the unquoted environment expansion. The exact formatting can vary by ShellCheck version, but it will identify the line and suggest adding quotes:

In deploy_report.sh line 6:
if [ $environment = production ]; then
     ^-----------^ SC2086: Double quote to prevent globbing and word splitting.

How the Code Works

A process flow showing a Bash script being analyzed by ShellCheck, warnings leading to code corrections, and a clean lint result proceeding to testing and deployment. The diagram also notes that linting does not replace testing.
ShellCheck statically analyzes Bash source, highlights quoting, expansion, and portability risks, and supports safer corrections before testing and deployment.

environment=$1 stores the first command-line argument, and config_file=$2 stores the second. For example, a deployment command might provide production and settings.conf as those arguments.

The problem is in this test:

[ $environment = production ]

When Bash expands an unquoted variable, its value can be split into multiple words. It can also be treated as a filename pattern if it contains wildcard characters. For example, an environment value containing spaces could change the number of words passed to the test command.

Quote the variable to keep its value as one argument:

if [ "$environment" = production ]; then
    echo "Deploying $config_file to $environment"
fi

In Bash, the [[ ... ]] conditional is also a clear choice for string comparisons:

if [[ "$environment" == "production" ]]; then
    printf 'Deploying %s to %s\n' "$config_file" "$environment"
fi

Both variables are quoted when they are used as values. The format string passed to printf is constant, while the variable values are supplied through %s placeholders.

ShellCheck warnings are recommendations, not commands that must always be followed blindly. Read the warning and understand the surrounding code before applying a change. In this example, the warning highlights a genuine safety and correctness problem.

Another Example

Here is a more complete deployment-check script. It validates the number of arguments, accepts only known environments, checks that the configuration file exists, and quotes every variable expansion:

#!/usr/bin/env bash

if (( $# != 2 )); then
    printf 'Usage: %s <staging|production> <config-file>\n' "$0" >&2
    exit 2
fi

environment=$1
config_file=$2

case "$environment" in
    staging|production)
        ;;
    *)
        printf 'Unknown environment: %s\n' "$environment" >&2
        exit 2
        ;;
esac

if [[ ! -f "$config_file" ]]; then
    printf 'Configuration file not found: %s\n' "$config_file" >&2
    exit 1
fi

printf 'Ready to deploy %s using %s\n' "$environment" "$config_file"

Run ShellCheck against this script:

shellcheck deploy_check.sh

This script should produce no ShellCheck warnings. It still needs tests for the deployment rules themselves, but linting has removed several common shell-language risks.

Before deployment, you should also verify that paths resolve as expected, especially when a deployment entry point is a symbolic link. The guide to inspect symbolic links in Bash is useful for checking that behavior separately from linting.

Common Mistakes

Quoting only some uses of a variable

Quoting a variable in one command does not make its other uses safe. Inspect every expansion, especially variables used as filenames, command arguments, or test values.

Assuming ShellCheck replaces testing

ShellCheck examines the script’s source code. It does not confirm that a file exists, that a deployment service is reachable, or that the script produces the desired result. Use linting together with tests and a safe staging environment.

Ignoring the script’s interpreter

A Bash script should identify Bash in its shebang:

#!/usr/bin/env bash

Some shell syntax works in Bash but not in a more minimal shell. Keeping the interpreter declaration accurate helps ShellCheck analyze the script with the intended shell in mind.

Using command substitution for a list of filenames

This pattern is risky:

for log_file in $(find "$log_dir" -name '*.log'); do
    process_log "$log_file"
done

Command substitution separates the result on whitespace. A filename containing spaces can therefore be split into multiple values. ShellCheck commonly warns about this pattern because it can cause a script to process the wrong paths.

Try It Yourself

Create a file named check_config.sh with the following script and run ShellCheck on it:

#!/usr/bin/env bash

config_file=$1

if [ -f $config_file ]; then
    printf 'Configuration exists: %s\n' "$config_file"
else
    printf 'Configuration is missing: %s\n' "$config_file"
fi

Fix the warning about the unquoted variable. Then run the script with a configuration path that contains a space and confirm that the corrected version handles it as one path.

Challenge

Write a script named find_error_logs.sh that:

  • Accepts a directory as its only command-line argument.
  • Searches that directory and its subdirectories for files ending in .log.
  • Prints the name of each log file containing the text ERROR.
  • Safely handles filenames containing spaces.
  • Produces no ShellCheck warnings.

Start with this intentionally unsafe version, then fix it and run shellcheck find_error_logs.sh:

#!/usr/bin/env bash

log_dir=$1

for log_file in $(find $log_dir -name "*.log"); do
    if grep -q ERROR $log_file; then
        echo "Found an error in $log_file"
    fi
done

Solution

The solution uses find‘s null-delimited output. The -print0 option separates filenames with a null character instead of a newline, and read -d '' reads each complete filename safely.

#!/usr/bin/env bash

if (( $# != 1 )); then
    printf 'Usage: %s <log-directory>\n' "$0" >&2
    exit 2
fi

log_dir=$1

if [[ ! -d "$log_dir" ]]; then
    printf 'Directory not found: %s\n' "$log_dir" >&2
    exit 1
fi

while IFS= read -r -d '' log_file; do
    if grep -q 'ERROR' "$log_file"; then
        printf 'Found an error in %s\n' "$log_file"
    fi
done < <(find "$log_dir" -type f -name '*.log' -print0)

The directory argument, the filename passed to grep, and the filename printed by printf are all quoted. The process substitution lets the loop read the results from find without using unsafe whitespace splitting. Run ShellCheck on this solution to verify that the lint warnings have been addressed.

Key Takeaways

  • ShellCheck statically analyzes shell scripts and reports likely mistakes before execution or deployment.
  • Quote variable expansions when their values should remain a single argument.
  • Command substitution is unsafe for lists of filenames because whitespace can split paths.
  • Use ShellCheck alongside tests; linting does not replace testing or deployment validation.
  • Run ShellCheck as part of your workflow before sharing or deploying Bash scripts.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Ad
Ad
Ad