Reviewing code of a shell script, I have seen that a change was made in one line:
Note: if the code contains errors it is because I have removed things trying to reduce it to a minimum to illustrate the question. The original code works correctly.
#!/bin/bash
if [ "$#" -eq 0 ]; then
echo "Error: se necesita al menos un argumento"
exit 1 # originariamente "return 1"
fi
return 0
He exit 1
was originally a return 1
. I don't quite understand why the was changed return 1
to a exit 1
, but not the return 0
to a exit 0
. Would there be any difference between the two in this case?
What is the difference between return
and exit
in Bash? And when should each be used?
In Bash, a
return
can only be used inside a function or in a file that we are going to dosource
. In these cases, it has the same value asexit
, which is to exit and return a status code that can be retrieved with$?
.In your code, then, the correct thing would be for both to
return
have been converted toexit
, since currently the script would not work well. In particular, if we execute it with an argument, it returns the error:Contrary to other languages, Bash does not have a
return
usage to use in functions. This is because of the very essence of using pipes: one command returns content to the next. In this way, what is done is to return through, for example, aecho
and then collect it by executing the command with$()
:The POSIX specification
return
warns us:So Bash made the decision that a
return
not work outside of a dot function or script (ie, by doing asource
). Other shells use other methods ( reference ).In Bash,
return
andexit
are synonyms, as explained in Bash Reference Manual → Definitions :Later he explains in Shell functions :
Some examples:
Executing this we have that it
$?
has value 23.