choice of control operators in scripts

Cristian Ionescu-Idbohrn cristian.ionescu-idbohrn at axis.com
Sun May 11 17:28:19 UTC 2008


The control operators I want to discuss are '||' vs. '&&' and how they
affect the exit status of the most recent pipeline '$?'.

I'll refer to the robustness of the scripts under testsuite.  In
particular runtest and testing.sh.

I think the '||' control operator is safer.  Please consider the following
script:

---8<---
#!/bin/sh

#set -e

status=12345

[ -z "$1" ] || eval "\$1=$1"
status=$?
echo "operator: '||'; status=$status"
echo "expecting 'status=0' when \$1 is not provided, and"
echo "          'status=127' when it is"

echo

[ -n "$1" ] && eval "\$1=$1"
status=$?
echo "operator: '&&'; status=$status"
echo "we'd like 'status=0' when \$1 is not provided" \
     "(but expecting 'status=1'), and"
echo "          'status=127' when it is"

echo
echo "just before 'exit 0'"

exit 0
---8<---

Running it with no (or one empty "") argument will produce (not really
good):

,----
| operator: '||'; status=0
| expecting 'status=0' when $1 is not provided, and
|           'status=127' when it is
|
| operator: '&&'; status=1
| we'd like 'status=0' when $1 is not provided (but expecting 'status=1'), and
|           'status=127' when it is
|
| just before 'exit 0'
`----

Running it with one argument shows (expected):

,----
| /tmp/test-status.sh: line 7: foo=foo: command not found
| operator: '||'; status=127
| expecting 'status=0' when $1 is not provided, and
|           'status=127' when it is
|
| /tmp/test-status.sh: line 15: foo=foo: command not found
| operator: '&&'; status=127
| we'd like 'status=0' when $1 is not provided (but expecting 'status=1'), and
|           'status=127' when it is
|
| just before 'exit 0'
`----

Please review and consider applying the attached patch (which cleans up
a few other small things too).  I did run ./runtest in testsuite before
and after applying the patch.  Results are identical.


Cheers,

-- 
Cristian
-------------- next part --------------
A non-text attachment was scrubbed...
Name: testsuite.0.patch
Type: text/x-diff
Size: 3075 bytes
Desc: 
Url : http://lists.busybox.net/pipermail/busybox/attachments/20080511/42db0c13/attachment.bin 


More information about the busybox mailing list