将参数存储到带有空格的变量中 [英] Store parameter into variable with space

查看:41
本文介绍了将参数存储到带有空格的变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下带有输出的命令:

Consider the following commands with output :

$ du -sm ~/Documents 
458 /home/utilisateur/Documents
$ du -sm ~/Documents --exclude='aa bb' --exclude='cc dd'
153 /home/utilisateur/Documents

我希望用这样的一个变量替换 excludes,以获得相同的输出.

I wish to replace the excludes by one variable like this, in order to get the same output.

$ du -sm ~/Documents "$c"

但是,如果我使用以下设置变量,我失败了.我测试过:

But, if I set variable with following, I failed. I tested :

$ c=--exclude='aa bb'\ --exclude='cc dd'
$ du -sm ~/Documents "$c"
458 /home/utilisateur/Documents

$ c="\"--exclude='aa bb' --exclude='cc dd'\""
$ du -sm ~/Documents $c
458 /home/utilisateur/Documents
du: cannot access '"--exclude='\''aa': No such file or directory
du: cannot access 'bb'\''': No such file or directory
du: cannot access 'dd'\''"': No such file or directory

$ c="--exclude='aa bb' --exclude='cc dd'"
$ du -sm ~/Documents "$c"
458 /home/utilisateur/Documents
$ du -sm ~/Documents $c
458 /home/utilisateur/Documents
du: cannot access 'bb'\''': No such file or directory
du: cannot access 'dd'\''': No such file or directory

请帮我改正错误.我知道这是关于引号的.

Please, could help me to fix my mistake. I know it's about quotes.

推荐答案

du --exclude='aa bb' --exclude='cc dd'

您有多个参数,其中至少有一些包含空格.无法将它们放在单个字符串变量中,以便保留参数之间的分隔.

You have multiple arguments, at least some of which contain whitespace. There's no way to put them in a single string variable so that the separation between the arguments is retained.

如果你这样做

args="--exclude=aa bb --exclude=cc dd"
du $args

字符串在所有空格处被拆分,为 du 提供四个不同的参数:--exclude=aabb--exclude=ccdd.

The string is split on all spaces, giving four different arguments to du: --exclude=aa, bb, --exclude=cc and dd.

另一方面,与

du "$args"

args 的内容根本没有拆分,所以 du 得到一个参数.

The contents of args aren't split, at all, so du gets a single argument.

引用没有帮助,因为它们在扩展变量后没有被处理,但是它们按字面意思转到命令,正如您从 du 给出的错误中看到的那样.

Quotes don't help, as they are not processed after expanding the variable, but they go to the command literally, as you saw from the errors du gave.

正确的解决方案是使用一个数组:

The correct solution is to use an array:

args=("--exclude=aa bb" "--exclude=cc dd")   # initialize it
args+=("--exclude=ee ff")                    # you can even append to it
du -sm ~/Documents "${args[@]}"

另见:为什么我的 shell 脚本会因空格或其他特殊字符而阻塞? 在 unix.SE 上

See also: Why does my shell script choke on whitespace or other special characters? on unix.SE

这篇关于将参数存储到带有空格的变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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