Return value linux command

Returning value from called function in a shell script

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 code is:

lockdir="somedir" test() < 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 return retval > retval=test() if [ "$retval" == "true" ] then echo "directory not created" else echo "directory already created" fi 

Not related to your question, but anyway. if you are trying to get a lock you may use «lockfile» command.

5 Answers 5

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 

Источник

How do bash return values of functions

I am trying to understand how do bash functions return values. I have created the 4 following functions, and I do not understand how it really works:

#test1.sh #!/bin/bash function a() < ls -la >function b() < _b=$(ls -la) >function c() < _c=$(ls -la) return $_c >function d() < _d=$(ls -la) return "$_d" >echo "A1:" a echo "----------" echo "A2:" ret_a=$(a) echo "$ret_a" echo "----------" echo "B1:" b echo "----------" echo "B2:" ret_b="$(b)" echo "$ret_b" echo "----------" echo "C1:" c echo "----------" echo "C2:" ret_c="$(c)" echo "$ret_c" echo "----------" echo "D1:" d echo "----------" echo "D2:" ret_d=$(d) echo "$ret_d" echo "----------" 
$ ./test1.sh A1: total 20 drwxrwxr-x 2 mayday mayday 4096 jul 15 09:18 . drwxrwxrwt 29 root root 12288 jul 15 11:46 .. -rwxrw-r-- 1 mayday mayday 523 jul 15 11:44 test1.sh ---------- A2: total 20 drwxrwxr-x 2 mayday mayday 4096 jul 15 09:18 . drwxrwxrwt 29 root root 12288 jul 15 11:46 .. -rwxrw-r-- 1 mayday mayday 523 jul 15 11:44 test1.sh ---------- B1: ---------- B2: ---------- C1: ./test1.sh: line 15: return: total: numeric argument required ---------- C2: ./test1.sh: line 15: return: total: numeric argument required ---------- D1: ./test1.sh: line 20: return: total 20 drwxrwxr-x 2 mayday mayday 4096 jul 15 09:18 . drwxrwxrwt 29 root root 12288 jul 15 11:46 .. -rwxrw-r-- 1 mayday mayday 523 jul 15 11:44 test1.sh: numeric argument required ---------- D2: ./test1.sh: line 20: return: total 20 drwxrwxr-x 2 mayday mayday 4096 jul 15 09:18 . drwxrwxrwt 29 root root 12288 jul 15 11:46 .. -rwxrw-r-- 1 mayday mayday 523 jul 15 11:44 test1.sh: numeric argument required 
  1. Does function a return the ls output without the return command? why?
  2. Why is different the return command from function c and function d ?
  3. What does the total: numeric argument required mean at function c and function d ?
  4. As summary, If i wanted to create a new function , that take into a variable the result of the ls executed in the previous function, what would be the best approach from the previous ones? i.e:
function ls_printer() < return $(ls -la) >function ls_printer_reader() < _my_variable=ls_printer echo "$_my_variable" >ls_printer_reader 

Источник

Читайте также:  Определение своего ip адреса linux

Bash Function Return Value

In Bash, functions do not support returning values like in other programming languages. Instead, the return value of a function is its exit status, a numeric value indicating success or failure. A zero exit status indicates success, while a non-zero exit status indicates failure.

Return values from a Bash function

Let’s understand return values from the bash function with examples.

Returning a status code

Although there exists a return statement, it can only be used to explicitly set the exit status code of a function. If a return statement is not specified in a Bash function, the exit status code is set equal to the status code of the last command executed in the function.

Consider the following script:

$ cat returnStatus.sh #!/bin/bash ## Return status of last statement function test_return_default() < echo "This should return 0, i.e. the status of echo command" >## Explicitly return 1 function test_return_explicit_status() < echo "The function failed during execution!" return 1 >test_return_default echo $? echo "" test_return_explicit_status echo $?

return status code 0

On executing the script, we see the following:

  • Function test_return_default returns the status of the echo statement i.e. 0.
  • In the function test_return_explicit_status, the status is explicitly returned using the return command.
  • The status code is set in the $? variable and can be accessed by the caller to make decisions.

Return a single value using the echo command

A single value can be easily returned from a function using the echo command which directs the output to the standard out. This value can be assigned to a variable in the caller.

$ cat returnUsingEcho.sh #!/bin/bash ## Echo the output string function func_do_two_plus_three() < echo "The result is $((2+3))" >## Echoed string is assigned to the result variable result=$(func_do_two_plus_three) echo $result

bash function return single value

Return multiple values using global variables

An easy way to return multiple values from a function is to set global variables in the function and reference the variables after the function.

$cat returnMultUsingGlobVar.sh #!/bin/bash ## Set global variables `result1`, `result2` in the function ## By default variables have global scope in Bash function func_do_multiple_math() < result1=$((2+3)) result2=$((4+7)) >func_do_multiple_math ## Access the global variables echo "The result 1 is $result1" echo "The result 2 is $result2"

return multiple values

Although this works, it is not considered a good programming practice, especially in larger scripts.

Return using function parameters

A better way to return multiple values is to pass parameters to the function and have local variables store the name of these passed parameters.

Читайте также:  Wireguard настройка client linux

Then, we can modify the passed parameters to store the result of the functions.

Consider the following script:

$cat returnUsingPassedParams.sh #!/bin/bash ## Local variables store the name of passed params function func_modify_passed_params() < local lresult1=$1 local lresult2=$2 eval $lresult1=$((2+3)) eval $lresult2=$((4+7)) >func_modify_passed_params result1 result2 echo "The result 1 is $result1" echo "The result 2 is $result2"

Return using function parameters

  • func_modify_passed_params result1 result2 passes the parameters result1, and result2 to the function.
  • local lresult1=$1 assigns the local variable lresult1 equal to the name of the first parameter i.e. result1.
  • eval $lresult1=$((2+3)) sets the variable referenced by lresult1 i.e. result1=5.

Error handling

Error handling is a very important concept in any programming language. It helps to handle errors gracefully and not terminate the program on running an erroneous command.

This concept of error handling applies to bash scripts in general but in this section let’s see how we can handle errors with the bash functions.

Consider the following bash function which attempts to perform division on the passed parameters.

$cat errorHandlingInBashFunc.sh #!/bin/bash function do_perform_division() < echo $((numerator/denominator)) >numerator=5 denominator=0 ## Invalid arithmetic result=$(do_perform_division numerator denominator)
  • It encounters a runtime error since the denominator=0 results in division by 0 which is invalid.
  • The script immediately terminates and prints the error to the user.

We can handle this error gracefully by pre-checking the denominator and returning from the function after setting the status code.

Using the returned status code in $? variable, we can print a useful message for the user.

$cat errorHandlingInBashFunc.sh #!/bin/bash function do_perform_division() < if [[ $denominator -eq 0 ]]; then return 1 fi echo $((numerator/denominator)) >numerator=6 denominator=0 ## Invalid arithmetic result=$(do_perform_division numerator denominator) if [[ $? -eq 1 ]]; then echo -e "Denominator should not be 0 for performing division\n" fi

Conclusion

Although Bash does not support returning values directly, there are other methods to return values from a function.

  • For simple functions, returning a single result, it is simpler to use the echo command to direct the output to a stdout and assign the result to a variable in the caller.
  • For functions returning 2 or more results, modifying the global variables in the function is a possible solution but this quickly gets cumbersome to deal with, especially in larger scripts.
  • Passing and modifying the parameters in a large function is a better method when dealing with multiple results.
  • Bash functions can return custom status codes which can be used to gracefully handle errors in the scripts and make decisions.

If this resource helped you, let us know your care by a Thanks Tweet. Tweet a thanks

Источник

Returning Values from Bash Functions

Bash screenshot from Wikipedia, https://en.wikipedia.org/wiki/Bash_(Unix_shell)

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. To return values, you can set a global variable with the result, or use command substitution, or you can pass in the name of a variable to use as the result variable. The examples below describe these different mechanisms.

Although bash has a return statement, the only thing you can specify with it is the function’s status, which is a numeric value like the value specified in an exit statement. The status value is stored in the $? variable. If a function does not contain a return statement, its status is set based on the status of the last statement executed in the function. To actually return arbitrary values to the caller you must use other mechanisms.

Читайте также:  Linux удалить часть файла

The simplest way to return a value from a bash function is to just set a global variable to the result. Since all variables in bash are global by default this is easy:

function myfunc()  myresult='some value' > myfunc echo $myresult 

The code above sets the global variable myresult to the function result. Reasonably simple, but as we all know, using global variables, particularly in large programs, can lead to difficult to find bugs.

A better approach is to use local variables in your functions. The problem then becomes how do you get the result to the caller. One mechanism is to use command substitution:

function myfunc()  local myresult='some value' echo "$myresult" > result=$(myfunc) # or result=`myfunc` echo $result 

Here the result is output to the stdout and the caller uses command substitution to capture the value in a variable. The variable can then be used as needed.

The other way to return a value is to write your function so that it accepts a variable name as part of its command line and then set that variable to the result of the function:

function myfunc()  local __resultvar=$1 local myresult='some value' eval $__resultvar="'$myresult'" > myfunc result echo $result 

Since we have the name of the variable to set stored in a variable, we can’t set the variable directly, we have to use eval to actually do the setting. The eval statement basically tells bash to interpret the line twice, the first interpretation above results in the string result='some value' which is then interpreted once more and ends up setting the caller’s variable.

When you store the name of the variable passed on the command line, make sure you store it in a local variable with a name that won’t be (unlikely to be) used by the caller (which is why I used __resultvar rather than just resultvar ). If you don’t, and the caller happens to choose the same name for their result variable as you use for storing the name, the result variable will not get set. For example, the following does not work:

function myfunc()  local result=$1 local myresult='some value' eval $result="'$myresult'" > myfunc result echo $result 

The reason it doesn’t work is because when eval does the second interpretation and evaluates result='some value' , result is now a local variable in the function, and so it gets set rather than setting the caller’s result variable.

For more flexibility, you may want to write your functions so that they combine both result variables and command substitution:

function myfunc()  local __resultvar=$1 local myresult='some value' if [[ "$__resultvar" ]]; then eval $__resultvar="'$myresult'" else echo "$myresult" fi > myfunc result echo $result result2=$(myfunc) echo $result2 

Here, if no variable name is passed to the function, the value is output to the standard output.

Mitch Frazier is an embedded systems programmer at Emerson Electric Co. Mitch has been a contributor to and a friend of Linux Journal since the early 2000s.

Источник

Оцените статью
Adblock
detector