如何删除环境变量的“SC2154”警告

use*_*578 5 bash shell lint shellcheck

在检查 shell 脚本时如何删除 shellcheck 的警告“SC2154”?

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

echo "proxy=$http_proxy" | sudo tee -a /etc/test.txt
Run Code Online (Sandbox Code Playgroud)

警告是“SC2154:引用了 http_proxy 但未分配。”

编辑:我想使用 sudo 将环境变量“http_proxy”写入 test.txt 文件。

Soc*_*owi 11

一般来说,更好的解决方案是遵守约定并以全部大写字母命名环境变量。但是,在这种情况下,我知道这http_proxy不是您的curl环境变量,而是由、等程序决定的wget,因此您不能简单地重命名它。


您可以通过注释抑制任何警告:

# shellcheck disable=SC2154
echo "proxy=$http_proxy" | ...
Run Code Online (Sandbox Code Playgroud)

http_proxy这将忽略从这一行开始的错误。随后$http_proxy也不会出错,但其他变量会出错。

要在中心位置禁用多个变量的警告,请将以下代码片段放在脚本的开头。警告: 脚本中第一个命令之前的 Shellcheck 指令将应用于整个脚本。作为解决方法,请true在指令上方放置一个虚拟命令(例如 )。

#! /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
Run Code Online (Sandbox Code Playgroud)