Click to See Complete Forum and Search --> : is ther a way to return strings from a BASH function?
CaptainPinko
07-01-2004, 06:09 PM
is there anyway to return a string from a BASH function from within a bash script? I've managed to get around it by making the function modify the value of a public variable.; but that is ugly since functions aren't supposed to have side-effects right? whenever I try to use 'return' it complains about the value not being numeric. I've scanned through TLDP and the man-page and haven'tfound anything... is there just no way to do it?
hlrguy
07-01-2004, 06:15 PM
Here is my bible link...
http://tille.soti.org/training/bash/
Chapter 11 covers function returns. How are you referencing it in your check? Or using it after the function call?
hlrguy
bwkaz
07-01-2004, 06:29 PM
There is no way to "return" a string in the same way you return a number. However, you can:
#!/bin/bash
function() {
echo "hello"
}
function
if [ $(function) = "hello" ] ; then
echo "equal"
else
echo "not equal"
fi Running this script prints:
hello
equal
Basically, he function echos the string that you want to "return", and then the caller uses process substitution to run the function and then capture that string.
CaptainPinko
07-01-2004, 06:48 PM
that was exactly what I was looking for!
for anyone else I did:
if [condition]
then
function2 "$(function1)"
fi
the literals were necessary as the returned string had spaces in it.
but I'm not familiar with the $(function) syntax. Is that one of the create sub-shell kind of things?
bwkaz
07-01-2004, 10:07 PM
It's bash's equivalent of the original Bourne shell's backticks. bash still supports backticks, but it has this alternate syntax because it's easier to nest (if you try to nest backticks, you need one level of escaping for each level of nesting; if you nest four levels of backticks, you'll need something like 5 or 7 backslashes before the innermost ones).
If you're not familiar with backticks, they run the program (or funciton) that you put inside them, collect its output, replace all runs of whitespace (spaces, tabs, newlines) with a single space, and then subsitute the result in where they are on the command line.
CaptainPinko
07-02-2004, 01:15 AM
Originally posted by bwkaz
It's bash's equivalent of the original Bourne shell's backticks. bash still supports backticks, but it has this alternate syntax because it's easier to nest (if you try to nest backticks, you need one level of escaping for each level of nesting; if you nest four levels of backticks, you'll need something like 5 or 7 backslashes before the innermost ones).
Awesome! Two for one! Points for you Bwkaz! I was just having that problem. It was only a single level of nesting, but I need another (or at least to make it nicer) but was avoiding for the very issue you mentioned. Thanks a lot!