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
A Bash function can't return a string directly like you want it to. You can do three things:
This is also true for some other shells.
Here's how to do each of those options:
1. Echo strings
2. Return exit status
3. Share variable
You are working way too hard. Your entire script should be:
but even that is probably too verbose. I would code it:
but the resulting error message is a bit obscure.
In case you have some parameters to pass to a function and want a value in return. Here I am passing "12345" as an argument to a function and after processing returning variable XYZ which will be assigned to VALUE
Output:
I think returning 0 for succ/1 for fail (glenn jackman) and olibre's clear and explanatory answer says it all; just to mention a kind of "combo" approach for cases where results are not binary and you'd prefer to set a variable rather than "echoing out" a result (for instance if your function is ALSO suppose to echo something, this approach will not work). What then? (below is Bourne Shell)
as in (yep, the example is somewhat silly, it's just an.. example)
If it's just a true/false test, have your function
return 0
for success, andreturn 1
for failure. The test would then be: