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
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.
The if statement is catching the return value of a command, for example with ls:
if ls -l; then
echo 'ok'
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With