繁体   English   中英

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

[英]Passing arguments to a command in Bash script with spaces

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

这是一个简单的例子。

#!/bin/bash -xv

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

ARG_BOTH="\"$ARG\" \"$ARG2\""
cat $ARG_BOTH

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

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

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[@]}"

产量

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

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

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

所以:

set "arg with spaces" "another thing with spaces"
cat "$@"

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

#! /bin/sh

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

cat "$ARG" "$ARG2"

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM