使用空格将参数传递给Bash脚本中的命令

Dou*_*kem 11 unix bash shell scripting escaping

我试图将2个参数传递给一个命令,每个参数都包含空格,我已经尝试转义args中的空格,我尝试用单引号括起来,我试过逃避\"但没有什么可行的.

这是一个简单的例子.

#!/bin/bash -xv

ARG="/tmp/a b/1.txt"
ARG2="/tmp/a b/2.txt"

ARG_BOTH="\"$ARG\" \"$ARG2\""
cat $ARG_BOTH
Run Code Online (Sandbox Code Playgroud)

它运行时我得到以下内容:

ARG_BOTH="$ARG $ARG2"
+ ARG_BOTH='/tmp/a\ b/1.txt /tmp/a\ b/2.txt'
cat $ARG_BOTH
+ cat '/tmp/a\' b/1.txt '/tmp/a\' b/2.txt
cat: /tmp/a\: No such file or directory
cat: b/1.txt: No such file or directory
cat: /tmp/a\: No such file or directory
cat: b/2.txt: No such file or directory
Run Code Online (Sandbox Code Playgroud)

Sie*_*geX 12

http://mywiki.wooledge.org/BashFAQ/050

TLDR

将你的args放在一个数组中并将你的程序称为 myutil "${arr[@]}"

#!/bin/bash -xv

file1="file with spaces 1"
file2="file with spaces 2"
echo "foo" > "$file1"
echo "bar" > "$file2"
arr=("$file1" "$file2")
cat "${arr[@]}"
Run Code Online (Sandbox Code Playgroud)

产量

file1="file with spaces 1"
+ file1='file with spaces 1'
file2="file with spaces 2"
+ file2='file with spaces 2'
echo "foo" > "$file1"
+ echo foo
echo "bar" > "$file2"
+ echo bar
arr=("$file1" "$file2")
+ arr=("$file1" "$file2")
cat "${arr[@]}"
+ cat 'file with spaces 1' 'file with spaces 2'
foo
bar
Run Code Online (Sandbox Code Playgroud)


Dig*_*oss 6

这可能是通用"set"命令的一个很好的用例,它将顶级shell参数设置为单词列表.也就是说,1美元,2美元......还要重置$*和$ @.

这为您提供了阵列的一些优点,同时保持了所有Posix-shell兼容性.

所以:

set "arg with spaces" "another thing with spaces"
cat "$@"
Run Code Online (Sandbox Code Playgroud)


zwo*_*wol 5

正确运行的示例shell脚本的最直接修订是:

#! /bin/sh

ARG="/tmp/a b/1.txt"
ARG2="/tmp/a b/2.txt"

cat "$ARG" "$ARG2"
Run Code Online (Sandbox Code Playgroud)

但是,如果你需要在一个shell变量中包含一大堆参数,那么你就是一条小溪; 没有便携,可靠的方法来做到这一点.(数组是特定于Bash的;唯一可移植的选项是,set并且eval两者都要求悲伤.)我认为需要这一点,以表明是时候用更强大的脚本语言重写,例如Perl或Python .