0

I have to make a conditional in ash, that depends on result of two commands. The problem is one of them returns the result to stdout, the other as exitcode.

Do I have to write

 command2
 RET=$?
 if [ `command1` -eq 1 -a $RET -eq 2 ] ; then ...

or is there some construct that would let me simply access return code of command2 within logic of [ ] ?

 if [ `command1` -eq 1 -a ${{{ command2 }}} -eq 2 ] ; then ...

( with ${{{ }}}} being the magical expression extracting the returncode ? )

SF.
  • 12,380
  • 11
  • 65
  • 102

2 Answers2

1

It would be better to write:

if [ "`command1`" -eq 1 ] && command2
then
  ....
fi

Or when you want to check if the exit code is 2 then:

if [ "`command1`" -eq 1 ] && { command2 ; [ "$?" = 2 ] ; }
then
  ....
fi

Example:

$ cat 1.sh
ARG="$1"

command1()
{
  echo 1
}
command2()
{
  return "$ARG"
}

if [ "`command1`" -eq 1 ] && { command2 ; [ "$?" = 2 ] ; }
then
  echo OK
else
  echo FAILED
fi

$ sh 1.sh 2
OK
$ sh 1.sh 3
FAILED
Igor Chubin
  • 51,940
  • 8
  • 108
  • 128
  • You need to quote like: `[ "\`command1\`" ... ]` otherwise everything will break unless the output splits to exactly one word. – Jo So Jul 03 '12 at 18:28
0

I guess there is no way to avoid $?, but I can use the command inside test statement, by adding ;echo $? at the end.

if [ `command1` -eq 1 -a `command2 ; echo $?` -eq 2 ] ; then ...
SF.
  • 12,380
  • 11
  • 65
  • 102