Returning value from called function in a shell script

后端 未结 5 524
自闭症患者
自闭症患者 2020-11-27 08:55

I want to return the value from a function called in a shell script. Perhaps I am missing the syntax. I tried using the global variables. But that is also not working. The c

5条回答
  •  悲&欢浪女
    2020-11-27 09:37

    A Bash function can't return a string directly like you want it to. You can do three things:

    1. Echo a string
    2. Return an exit status, which is a number, not a string
    3. Share a variable

    This is also true for some other shells.

    Here's how to do each of those options:

    1. Echo strings

    lockdir="somedir"
    testlock(){
        retval=""
        if mkdir "$lockdir"
        then # Directory did not exist, but it was created successfully
             echo >&2 "successfully acquired lock: $lockdir"
             retval="true"
        else
             echo >&2 "cannot acquire lock, giving up on $lockdir"
             retval="false"
        fi
        echo "$retval"
    }
    
    retval=$( testlock )
    if [ "$retval" == "true" ]
    then
         echo "directory not created"
    else
         echo "directory already created"
    fi
    

    2. Return exit status

    lockdir="somedir"
    testlock(){
        if mkdir "$lockdir"
        then # Directory did not exist, but was created successfully
             echo >&2 "successfully acquired lock: $lockdir"
             retval=0
        else
             echo >&2 "cannot acquire lock, giving up on $lockdir"
             retval=1
        fi
        return "$retval"
    }
    
    testlock
    retval=$?
    if [ "$retval" == 0 ]
    then
         echo "directory not created"
    else
         echo "directory already created"
    fi
    

    3. Share variable

    lockdir="somedir"
    retval=-1
    testlock(){
        if mkdir "$lockdir"
        then # Directory did not exist, but it was created successfully
             echo >&2 "successfully acquired lock: $lockdir"
             retval=0
        else
             echo >&2 "cannot acquire lock, giving up on $lockdir"
             retval=1
        fi
    }
    
    testlock
    if [ "$retval" == 0 ]
    then
         echo "directory not created"
    else
         echo "directory already created"
    fi
    

提交回复
热议问题