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
原文地址:https://www.cnblogs.com/lxw0109/p/return_value_shell.html