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 "----------"
When I execute ./test1.sh it provides me the following output:
$ ./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
My questions are:
- Does
function areturn thelsoutput without thereturncommand? why? - Why is different the
returncommand fromfunction candfunction d? - What does the
total: numeric argument requiredmean atfunction candfunction d? - 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
Nwhich is> 255then the real return value will beN % 256. a command's return value will be saved in$?. (2) shell's$( command ... )is used to get the output of the command. the result is a string.ls) inherit their standard output from the function.