使用eval命令解决shell脚本中函数嵌套调用中的参数问题

先看一个例子:

#!/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.

原文地址:https://www.cnblogs.com/opangle/p/2653722.html