为什么两种情况下的真实价值测试都会恢复正值?

时间:2019-04-16 09:45:05

标签: bash

这是我的脚本simple.sh

function b() {
    local a;
    a=$1

        [[ "$a" =~ ^yes* ]]
}


function main(){
    local test;
    test=$(b $1)
        if [[ ${test} ]]; then
        echo Positive I am all good
        fi
        echo The end
}

main $@

我希望如果我运行bash simple.sh yes它将打印

Positive I am all good
The end

但是如果我运行bash simple.sh no,它应该会打印

The end

但是,当我在shell中运行脚本时,都可以打印

The end

为什么?

我正在使用Ubuntu Xenial。

如果我添加-x标志,我会看到以下踪迹:

$ bash -x simple.sh yes
+ main yes
+ local test
++ b yes
++ local a
++ a=yes
++ [[ yes =~ ^yes* ]]
+ test=
+ [[ -n '' ]]
+ echo The end
The end

$ bash -x simple.sh no
+ main no
+ local test
++ b no
++ local a
++ a=no
++ [[ no =~ ^yes* ]]
+ test=
+ [[ -n '' ]]
+ echo The end
The end

test为空白

bash版本是

bash --version
GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

2 个答案:

答案 0 :(得分:3)

带有以下行:

test=$(b $1)

您正在将函数b的标准输出存储在变量test中,但是函数b没有输出,它仅具有返回值 ,不存储。 test变量将始终为空。

要使用函数的返回值,应使用$?来存储在test中,您有两个选择:

  • 调用if
  • 中的函数
function b() {
    local a;
    a="$1"

    [[ "$a" =~ ^yes* ]]
}


function main(){
    if  b "$1"; then            # The if will evaluate the return value (0 means true)
        echo "Positive I am all good"
    fi
    echo The end
}

main $@
  • 存储返回值并在if
  • 中求值
function b() {
    local a;
    a="$1"

    [[ "$a" =~ ^yes* ]]
}


function main(){
    local test;
    b $1
    test="$?"
    if [ "${test}" -eq 0 ]; then    # You need to manually evaluate for 0
        echo "Positive I am all good"
    fi
    echo "The end"
}

main $@

答案 1 :(得分:1)

我个人更喜欢上面很多人建议的if函数方法,但是,如果您想使main函数与以前的函数相同,也可以返回一个返回值:

function b() {
    if [[ "$1" =~ ^yes* ]]; then
     echo "success"
    fi
}


function main(){
    local test;
    test=$(b $1)
    if [[ ${test} ]]; then
      echo Positive I am all good
    fi
    echo The end
}

main $@in $@
相关问题