bashshelllintshellcheck

How can I remove the "SC2154" warning for environment variables


How can I remove shellcheck's warning "SC2154" when linting the shell script?

#!/bin/bash
set -euo pipefail
IFS=$'\n\t'

echo "proxy=$http_proxy" | sudo tee -a /etc/test.txt

The warning is "SC2154: http_proxy is referenced but not assigned."

EDIT: I want to write the environment variable "http_proxy" to the test.txt file using sudo.


Solution

  • In general, the better solution would be to stick to the convention and name your environment variables in ALL_CAPS. However, in this case I understand that http_proxy is not your environment variable, but is dictated by programs like curl, wget, and so on, so you cannot simply rename it.


    You can suppress any warning with a comment:

    # shellcheck disable=SC2154
    echo "proxy=$http_proxy" | ...
    

    This will ignore the error about http_proxy starting from this line. Subsequent $http_proxy won't give errors either, but other variables will.

    To disable the warnings for multiple variables in a central place, put below snippet at the beginning of your script. Warning: Shellcheck directives before the first command in your script will apply to the whole script. As a workaround, put a dummy command (e.g. true) above the directive.

    #! /bin/bash
    # Using "shellcheck disable=SC2154" here would ignore warnings for all variables
    true
    # Ignore only warnings for the three proxy variables
    # shellcheck disable=SC2154
    echo "$http_proxy $https_proxy $no_proxy" > /dev/null