zoukankan      html  css  js  c++  java
  • func && operation_yes || operation_no (Shell)

      通过&&, || 理解shell中的函数返回值。

      我想实现如下功能:

      写一个函数判断一个字符串中是否只包含数字,并返回相应的标志(是/否);

      通过调用上面的函数,判断给定的字符串是否只包含数字,根据返回值做不同的处理。

      问题出现了,当只包含数字时我让函数返回1(想用1表示真),否则返回0.

      然后通过func && operation_yes || operation_no.结果就出现了判断情况正好相反的现象。

      原因就是我对shell函数的返回值按照C/C++,Python,Java...的方式理解了,而正确的理解是:

      Bash functions, unlike functions in most programming languages do not allow you to return a value to the

    caller. When a bash function ends its return value is its status: zero for success, non-zero for failure.

    通过下面的func2理解这种现象(下面的代码是能够正确判断的版本,正好判断相反的版本,就是对func2中return

    0和1进行调换即可):

    #!/bin/bash
    #File: demo.sh
    #Author: lxw
    #Time: 2014-12-21
    
    func1()
    {
        echo "-----------123a-----------------------"
        [ -z $(echo "123a"|sed 's/[0-9]//g') ] && echo "all digits" || echo "not all digits"
    }
    
    func2()
    {
        echo "-----------123-----------------------"
        [ -z $(echo "123"|sed 's/[0-9]//g') ] && return 0 || return 1
        #                        return value:    0_yes         1_no
    }
    
    func1
    echo "func1() returns" $?
    
    func2
    #函数的返回值实际上就是函数的退出状态
    echo "func2() returns" $?
    func2 && echo "all digits" || echo "not all digits"

      所以当执行最后一条语句时,&&,||根据func2函数的执行状态,决定执行哪部分代码。

    执行结果:

    -----------123a-----------------------
    not all digits
    func1() returns 0
    -----------123-----------------------
    func2() returns 0
    -----------123-----------------------
    all digits
  • 相关阅读:
    php模拟发送GET和POST请求
    php获取从百度搜索进入网站的关键词
    HDU 6218 (线段树+set)
    Wannafly挑战赛2_D Delete(拓扑序+最短路+线段树)
    BZOJ3926 (后缀自动机)
    Codeforces 848C (cdq分治)
    CERC 2014 (动态树+主席树)
    UOJ 58 (树上带修改的莫队)
    UVA12345 (带修改的莫队)
    BZOJ2038 (莫队)
  • 原文地址:https://www.cnblogs.com/lxw0109/p/return_value_shell.html
Copyright © 2011-2022 走看看