Bash参数替换 [英] Bash parameter substitution

查看:59
本文介绍了Bash参数替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习bash参数替换,并且有一个非常基本的问题:

I am trying to learn bash parameter substitution and have a very basic question:

为什么这样做:

#!/bin/sh
v1="-E"
v2="s/./x/g"
sed "$v1" "$v2" <<<"abc" # result = "xxx"

但这不起作用:

#!/bin/sh
v1="-E"
v2="s/./x/g"
sed "$v1 $v2" <<<"abc" # result = "sed: illegal option..."

我正在使用Mac OS X bash.

I am using Mac OS X bash.

推荐答案

由于第二个示例(错误的示例)使用的引号是错误的.使用引号来指定必须将变量产生的结果视为字符串,然后在其中一个变量中添加了两个变量.每个变量都必须分开,因为这样就好比说它的一个变量,所以sed看到一个变量而不是两个.例如,让我们说:

Because on the second example, (the wrong one) you are using the quotes wrong. The quotes are being used in order to specify that what whatever comes out of that variable has to be treated as a string, and you added two variables in one of them. each one has to be seperated, because like this its like saying its one variable, so sed sees one variable not two. So for example, lets say:

v1=123
v2=456

在第二个示例中,如sed所示,sed将看到:"123456",尽管sed希望看到的是两个变量,一个具有123,第二个具有456.这就是为什么应该拥有它们的原因.用引号引起来!我希望我对它的解释足够好,让您理解!!

as you have it on the second example, sed will see this: "123456", though what you want sed to see is two variables, one to have 123 and the second one to have 456. Thats why you should have them in seperated quotes! I hope i explained it good enough for you to understand!!

PS

您在第二个示例中实际执行的操作是,如果您要归并两个变量并将它们作为字符串添加到另一个变量中,则可以在某个时候使用它:)

What you actually did on the second example, you could use it at some point if you want to concutenate two variables, and add them in another as a string :)

更新

所以让我们在这里举个例子.....

So lets have an example here.....

v1=123
v2=456
CASE1="$v1" "$v2"
CASE2="$v1 $v2"
echo CASE1
echo CASE2

对于CASE1,输出将为123456,对于CASE2,输出将为123 456....两种方式都可以完成并打印出相同内容的唯一方法是.....

For the CASE1 the output would be 123456, as for the CASE2 the output would be 123 456..... Do you get the difference now? The only way to do it in both ways and print out the same thing would be this.....

v1=123
v2=456
CASE1="$v1" "$v2"
CASE2="$v1$v2"

case2在变量之间没有空格...

having the case2 WITHOUT a space between the variables...

这篇关于Bash参数替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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