如何在脚本启动时隐藏部分未使用的变量

hoc*_*ock 3 linux bash shell

在这种情况下,如何在未使用 bash 命令定义变量时隐藏变量的使用:

EXCLUDE_PORTS="--exclude-ports $2"

if [ "${EXCLUDE_PORTS:-}" == "" ]; then
    EXCLUDE_PORTS=''
fi
Run Code Online (Sandbox Code Playgroud)

我还需要隐藏 --exclude-ports,当未指定 $2 时。实际上,当我没有在脚本启动时指定 $2 时,脚本只取第一部分为空的“--exclude-ports”,这破坏了我的脚本。

Léa*_*ris 5

动态构建参数时始终使用/首选数组:

if [ -n "$2" ]
then EXCLUDE_PORTS=( '--exclude-ports' "$2" )
else EXCLUDE_PORTS=()
fi

echo command "${EXCLUDE_PORTS[@]}" --other-option
Run Code Online (Sandbox Code Playgroud)