将参数传递给具有空格的Bash脚本中的命令 [英] Passing arguments to a command in Bash script with spaces

查看:144
本文介绍了将参数传递给具有空格的Bash脚本中的命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图传递2个参数到一个命令,每个参数包含空格,我已经尝试转义在args中的空格,我尝试用单引号包装,我试过转义\但没有将会工作。



这是一个简单的例子。

 #! bin / bash -xv 

ARG =/ tmp / ab / 1.txt
ARG2 =/ tmp / ab / 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\:没有这样的文件或目录
cat:b / 1.txt:没有这样的文件或目录
cat:/ tmp / a\:没有这样的文件或目录
cat:b / 2.txt:没有这样的文件或目录
pre>

解决方案

请参阅 http://mywiki.wooledge.org/BashFAQ/050



TLDR



将您的参数置于数组中,并将您的程序称为 myutil$ {arr [@]} / p>

 #!/ bin / bash -xv 

file1 =带空格1的文件
file2 =带空格2的文件
echofoo> $ file1
echobar> $ file2
arr =($ file1$ file2)
cat$ {arr [@]}



输出



  file1 =带空格1的文件
+ file1 ='带空格1'的文件
file2 =带空格2的文件
+ file2 ='带空格2的文件'
echofoo> $ file1
+ echo foo
echobar> $ file2
+ echo bar
arr =($ file1$ file2)
+ arr =($ file1$ file2)
cat $ {arr [@]}
+ cat'文件与空格1''文件与空格2'
foo
bar


I'm trying to pass 2 arguments to a command and each argument contains spaces, I've tried escaping the spaces in the args, I've tried wrapping in single quotes, I've tried escaping \" but nothing will work.

Here's a simple example.

#!/bin/bash -xv

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

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

I'm getting the following when it runs:

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

解决方案

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

TLDR

Put your args in an array and call your program as 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[@]}"

Output

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

这篇关于将参数传递给具有空格的Bash脚本中的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆