在字符串中嵌入命令 [英] Embedding commands in strings

查看:121
本文介绍了在字符串中嵌入命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下几点:

#!/bin/tcsh

set thing = 'marker:echo "quoted argument"'
set a = `echo "$thing" | sed 's/\([^:]*\):\(.*\)/\1/'`
set b = `echo "$thing" | sed 's/\([^:]*\):\(.*\)/\2/'`
echo $a
echo $b
$b
echo "quoted argument"

这给了

marker
echo "quoted argument"
"quoted argument"
quoted argument

如果 $ B 回声报援引论据,为什么评估 $ B 给从一个不同的结果回声报援引论据

If $b is echo "quoted argument", why does evaluating $b give a different result from echo "quoted argument"?

因为我知道的tcsh 是可怕的(但它是我必须用于工作),这里是猛砸同样的问题:

Since I know tcsh is awful (but it's what I have to use for work), here is the same problem in Bash:

thing='marker:echo "quoted argument"'
a=`echo "$thing" | sed 's/\(.*\):\([^:]*\)/\1/'`
b=`echo "$thing" | sed 's/\(.*\):\([^:]*\)/\2/'`
echo $a
echo $b
$b
echo "quoted argument"

的输出是相同的。需要注意的是,被我击这样做,我肯定会使用的地图。我没有这样的奢侈:)。该解决方案必须以的tcsh 工作

The output is the same. Note that, were I doing this in Bash, I would certainly use a map. I do not have that luxury :). The solution must work in tcsh.

我想 $ B 来表现,就好像我自己输入的命令,因为我看到它:

I would like $b to behave just as if I typed the command in myself as I see it:

marker
echo "quoted argument"
quoted argument
quoted argument

<子>这是一个后续问题来访问数组元素在TCSH 空间。

推荐答案

是啊,评估是解决方案在这里(以及解决方案是不是有一个命令摆在首位的字符串请参见 http://mywiki.wooledge.org/BashFAQ/050 为以上)。

Yeah, eval is the "solution" here (well the solution is not to have a command in a string in the first place see http://mywiki.wooledge.org/BashFAQ/050 for more).

究其原因,你看到的报价,当您运行 $ B 是因为shell命令的评价的顺序。该外壳程序的最后一步,所有其他扩展后,是远程引号(但它不会删除造成的任何扩展的引号)。

The reason you see the quotes when you run $b is because of the order of evaluation of a shell command. The very last thing that the shell does, after all other expansions, is to remote quotes (however it doesn't remove quotes that resulted from any of the expansions).

所以,当你有 B ='回声报援引论据及运行 $ B 作为命令行会发生什么是变量扩展让你获得回声报援引论据然后就是运行原样。

So when you have b='echo "quoted arguments"' and run $b as the command line what happens is that the variable is expanded so you get echo "quoted arguments" and then that is run as-is.

$ c ()
{
    printf 'argc: %s\n' "$#";
    printf 'argv: %s\n' "$@"
}

$ b='echo "quoted arguments"'

$ c "quoted arguments"
argc: 1
argv: quoted arguments
$ c $b
argc: 3
argv: echo
argv: "quoted
argv: arguments"
$ c "$b"
argc: 1
argv: echo "quoted arguments"
$ eval c $b
argc: 2
argv: echo
argv: quoted arguments
$ eval c "$b"
argc: 2
argv: echo
argv: quoted arguments

这篇关于在字符串中嵌入命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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