长路漫漫

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

先看一个例子:

#!/bin/bash

fun1()
{
    $1
    if [ $? -ne 0 ]
    then
        echo Failed executing $1
        exit 1
    fi
}

fun2()
{
    echo $1
#    return 0 or 1
}

fun1 "fun2 \"that is right\""

输出结果为:

"that

我们期待的结果应该为:

that is right 

为什么会这样呢?实际上,例子中实际调用fun1()时,$1为fun2 \"that is right\",因此fun2()中的$1就成了"that。使用eval命令可以解决此问题,修改如下:

#!/bin/bash

fun1()
{
    eval $1   # use eval
    if [ $? -ne 0 ]
    then
        echo Failed executing $1
        exit 1
    fi
}

fun2()
{
    echo $1
#    return 0 or 1
}

fun1 "fun2 \"that is right\""

这样就符合我们的预期了。

eval用法如下:

eval [arg ...]

【说明】: eval会读取它的所有参数,然后将它们组成一条单独的命令,并在shell中执行(其返回值会返回给eval,然后eval返回同样的值)。eval的帮助文档描述如下:

eval [arg ...]

The args are read and concatenated together into a single command.  This command is then read  and  executed  by the shell, and its exit status is returned as the value of eval. If there are no args, or only null arguments, eval returns 0.

posted on 2012-08-24 11:05  opangle  阅读(2124)  评论(0编辑  收藏  举报