Returns 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

$rcontains tor f, but also the output of the command ls.

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

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

+5
source share
4 answers

The shell function can return a numeric value. Consider 0 and 1, not 'f' and 't'

#!/bin/sh

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

a
r=$?
echo $r

This will still write the output from ls -1 a*which you probably still want to delete, but the value rwill be 0 or 1 and will not include the output.

, , , , ( , ls )

+4

ls , a.

a() {
  shopt -s nullglob
  ret="f"
  for file in a*
  do   
    ret="t"
    break
  done
  echo "$ret"
}
+1

:

{
  command1
  command2
} >/dev/null

- script - , exec builtin:

echo interesting
exec >/dev/null
echo boring

, script, . , .

exec /dev/null, . , . , , , , , , .

{
  exec 3>&1         # duplicate fd 3 to fd 1 (standard output)
  exec >/dev/null   # connect standard output to /dev/null
  echo boring
  exec 1>&3         # connect standard output back to what was saved in fd 3
  echo interesting
  exec >/dev/null   # connect standard output to /dev/null again
  echo more boring
} 3>/dev/null       # The braced list must have its fd 3 connected somewhere,
                    # even though nothing will actually be written to it.
+1
source
a() { 
ls -1 a*  > /dev/null
[ "$?" == "0" ] && echo t  || echo f

} 

r=`a` 
echo $r 

Consider using [-f filename] and other files.

0
source

All Articles