Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get test command return code in the shell?

Is it any better way to get return code from command in one line. eg:

$ test $(ls -l) ||echo 'ok'
-bash: test: too many arguments
ok

the above script have error in test command, because it seems parsing the output "ls - l" not return code.

I know use the "if" syntax is work fine, But need more then one lines.

ls -l
if [ $? -eq 0 ];then
   echo 'ok'
fi
like image 767
Robber Pen Avatar asked May 03 '16 11:05

Robber Pen


2 Answers

You can use && and || to make these things one-liner. For example, in the following:

ls -l && echo ok

echo ok will run only if the command before && (ls -l) returned 0.

On the other hand, in the following:

ls -l || echo 'not ok'

echo 'not ok' will run only if the command before || returned non zero.

Also, you can make your if..else block one-liner using ;:

if ls -l;then echo ok;else echo 'not ok';fi

But this may make your code hard to read, so not recommended.

like image 189
Jahid Avatar answered Sep 22 '22 06:09

Jahid


The if statement is catching the return value of a command, for example with ls:

if ls -l; then
    echo 'ok'
fi
like image 30
oliv Avatar answered Sep 21 '22 06:09

oliv