大网数据广告活动
服务器运维问答

quote only if variable is non-empty

· 52CE 我爱测

I have an ancient bash script that I'd like to improve. This script used many variables and in some cases some of the variables are referenced but empty or unset. This is generally not a problem here because the script has been d…

问题原文

原帖链接 · uli42 · CC BY-SA 3.0

I have an ancient bash script that I'd like to improve. This script used many variables and in some cases some of the variables are referenced but empty or unset. This is generally not a problem here because the script has been designed like this from the beginning.

However, I have started to use shellcheck which complains about missing quotes a lot. So I have added quotes and came across an inconvience for which I do not have a nice solution.

There are many lines that look like this:

cmd $param1 $param2 $param3 $param4

If one of the params is empty or unset it is still working and the number of params that cmd gets is reduced. But if I start adding quotes

cmd "$param1" "$param2" "$param3" "$param4"

cmd will always get 4 params, no matter if any of them is empty.

Why it is like that is perfectly clear. The workaround is also clear (checking for emptyness before using the param) but it is ugly and requires a lot of additional code.

So I am looking for clever solution that either a) omits a param (including the quotes!) if it is empty b) adds the quoting only for non-empty variables

已采纳解答

原帖链接 · glenn jackman · CC BY-SA 3.0

What shell are you using for this script? I assume it's /bin/sh

The only array-like entity you have in a POSIX shell is the positional parameters. You could do this:

set --  # clear the positional parameters
for param in "$param1" "$param2" "$param3" "$param4"; do
    if [ -n "$param" ]; then
        # append this param to the positional params
        set -- "$@" "$param"
    fi
done
# invoke the command with the positional params, properly quoted
cmd "$@"

If you wanted to get cleverer about it, wrap the invocation of cmd in a function:

invoke_cmd() {
  n="$#"  # remember the original number of params
  # append to the args list only if non-empty                    
  for arg; do [ -n "$arg" ] && set -- "$@" "$arg"; done
  # discard the original params (including the empty ones)
  shift "$n"
  # and invoke the cmd
  cmd "$@"
}
invoke_cmd "$param1" "$param2" "$param3" "$param4"

For actual bash, simplify

invoke_cmd() {
  local args=()
  for arg; do [[ "$arg" ]] && args+=("$arg"); done
  cmd "${args[@]}"
}
invoke_cmd "$param1" "$param2" "$param3" "$param4"

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-08-10)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。