BASH Shell使用变量中的空格扩展参数

Ste*_*ies 2 unix bash shell arguments spaces

说我有一个$ARGS包含以下内容的变量:

file1.txt "second file.txt" file3.txt
Run Code Online (Sandbox Code Playgroud)

如何将$ARGSas参数的内容传递给命令(例如cat $ARGS,说),将其"second file.txt"视为一个参数而不将其拆分为"secondand file.txt"

理想情况下,我希望能够将参数准确地传递给任何存储在变量中的命令(从文本文件中读取,但我认为这不相关)。

谢谢!

Cha*_*ffy 5

可以不使用bash数组或来执行此操作eval:这是xargs不使用-0or或-d扩展名(大多数情况下会产生错误的行为)实际上有用的少数几个地方之一。

# this will print each argument on a different line
# ...note that it breaks with arguments containing literal newlines!
xargs printf '%s\n' <<<"$ARGS"
Run Code Online (Sandbox Code Playgroud)

...要么...

# this will emit arguments in a NUL-delimited stream
xargs printf '%s\0' <<<"$ARGS"

# in bash 4.4, you can read this into an array like so:
readarray -t -d '' args < <(xargs printf '%s\0' <<<"$ARGS")
yourprog "${args[@]}" # actually run your programs

# in bash 3.x or newer, it's just a bit longer:
args=( );
while IFS= read -r -d '' arg; do
    args+=( "$arg" )
done < <(xargs printf '%s\0' <<<"$ARGS")
yourprog "${args[@]}" # actually run your program

# in POSIX sh, you can't safely handle arguments with literal newlines
# ...but, barring that, can do it like this:
set --
while IFS= read -r arg; do
    set -- "$@" "$arg"
done < <(printf '%s\n' "$ARGS" | xargs printf '%s\n')
yourprog "$@" # actually run your program
Run Code Online (Sandbox Code Playgroud)

...或者让它xargs自己进行调用:

# this will call yourprog with ARGS given
# ...but -- beware! -- will cause bugs if there are more arguments than will fit on one
# ...command line invocation.
printf '%s\n' "$ARGS" | xargs yourprog
Run Code Online (Sandbox Code Playgroud)