Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a single value from a shell script function

Example:

#!/bin/sh

a() {
R=f
ls -1 a*
[ "$?" == "1" ] && { R=t; }
echo $R
}

r=`a`
echo $r

$r contains t or f but also the output of the ls command.

I may write ls -1 a* >/dev/null 2>/dev/null, but if there is a more complex script that can be lead to errors.

Is there any way to return a single value from a() ?

like image 958
PeterMmm Avatar asked Jun 29 '10 10:06

PeterMmm


2 Answers

A shell function can return a numeric value. Consider 0 and 1 rather than 'f' and 't'

#!/bin/sh

a() {
R=0
ls -1 a*
[ "$?" == "1" ] && { R=1; }
return $R
}

a
r=$?
echo $r

This will still write output from the ls -1 a* which you probably still want to dispose of, but the value of r will be either 0 or 1 and won't include the output.

The other examples of redirecting output either from a line or a whole block are good, and, as others suggested, you should get to know other ways to test for conditions (but I was assuming the ls was kind of an arbitrary example)

like image 53
Stephen P Avatar answered Sep 27 '22 16:09

Stephen P


you don't have to use ls to check for files starting with a. Just use the shell

a() {
  shopt -s nullglob
  ret="f"
  for file in a*
  do   
    ret="t"
    break
  done
  echo "$ret"
}
like image 32
ghostdog74 Avatar answered Sep 27 '22 17:09

ghostdog74