传递参数给一个命令在Bash脚本用空格 [英] Passing arguments to a command in Bash script with spaces

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

问题描述

我想通过2参数的命令和每个参数包含空格,我试过在ARGS逃脱的空间,我在单引号试过包裹,我已经试过逃跑\\,但什么都不会的工作。

下面是一个简单的例子。

 #!/斌/ bash的-xvARG =/ tmp目录/ A B /的1.txt
ARG2 =/ tmp目录/ A B / 2.txtARG_BOTH =\\$ ARG \\\\$ ARG2 \\
猫$ ARG_BOTH

我得到以下运行时:

  ARG_BOTH =$ ARG $ ARG2
+ ARG_BOTH ='/ tmp目录/ A \\ B /的1.txt的/ tmp / A \\ B / 2.txt
猫$ ARG_BOTH
+猫的/ tmp / A \\'B /的1.txt'的/ tmp / A \\'B / 2.txt
猫:/ tmp目录/ A \\:没有这样的文件或目录
猫:B /的1.txt:没有这样的文件或目录
猫:/ tmp目录/ A \\:没有这样的文件或目录
猫:B / 2.txt:没有这样的文件或目录


解决方案

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

TLDR

把你的AR​​GS在数组中,并调用程序为 myutil$ {ARR [@]}

 #!/斌/ bash的-xv文件1 =文件,用空格1
文件2 =文件,用空格2
回声富> $文件1
回声酒吧> $文件2
ARR =($文件1$文件2)
猫$ {ARR [@]}

输出

 文件1 =用空格1文件
+文件1 ='用空格1文件'
文件2 =文件,用空格2
+文件2 ='用空格2文件
回声富> $文件1
+ foo的回声
回声酒吧> $文件2
+回声酒吧
ARR =($文件1$文件2)
+ ARR =($文件1$文件2)
猫$ {ARR [@]}
+猫'的文件用空格2''用空格1文件'

酒吧

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天全站免登陆