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.

  • 相关阅读:
    当前信息型强人工智能发展缺失条件--规则
    假象篇(1)-动态可变参数的神经网络
    02梦断代码阅读笔记
    结队开发之NABCD
    01梦断代码阅读笔记
    03构建之法阅读笔记
    进度3
    02构建之法阅读笔记
    01构建之法阅读笔记
    关于最大子序和的算法问题(二)
  • 原文地址:https://www.cnblogs.com/opangle/p/2653722.html
Copyright © 2011-2022 走看看