如果您想以一种适用于每个可能的命令行参数(带有空格的值、带有换行符的值、带有文字引号字符的值、不可打印的值、带有全局字符的值等)的稳健方式执行此操作,它变得更有趣了。
要写入文件,给定参数数组:
printf '%s\0' "${arguments[@]}" >file
...酌情替换为"argument one"、"argument two"等。
从该文件中读取并使用其内容(在 bash、ksh93 或其他最近的带有数组的 shell 中):
declare -a args=()
while IFS='' read -r -d '' item; do
args+=( "$item" )
done <file
run_your_command "${args[@]}"
从该文件中读取并使用其内容(在没有数组的 shell 中;请注意,这将覆盖您的本地命令行参数列表,因此最好在函数内部完成,这样您就可以覆盖函数的参数而不是全局列表):
set --
while IFS='' read -r -d '' item; do
set -- "$@" "$item"
done <file
run_your_command "$@"
请注意,-d(允许使用不同的行尾分隔符)是非 POSIX 扩展,没有数组的 shell 也可能不支持它。如果是这种情况,您可能需要使用非 shell 语言将 NUL 分隔的内容转换为 eval-safe 形式:
quoted_list() {
## Works with either Python 2.x or 3.x
python -c '
import sys, pipes, shlex
quote = pipes.quote if hasattr(pipes, "quote") else shlex.quote
print(" ".join([quote(s) for s in sys.stdin.read().split("\0")][:-1]))
'
}
eval "set -- $(quoted_list <file)"
run_your_command "$@"