zoukankan      html  css  js  c++  java
  • 使用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.

  • 相关阅读:
    SSL配置
    PHPStorm 打开时闪退的问题
    【网址链接】
    js中将string转换为number
    HTML特效代码大全
    前端面试题-重要
    元素框默认的计算方式
    html中有趣的显示出柠檬的方法
    html中圆角方法border-top-left-radius
    html+css显示出三角形方法transparent
  • 原文地址:https://www.cnblogs.com/opangle/p/2653722.html
Copyright © 2011-2022 走看看