In bash, I know I should use &&
if I want a command B
to be run only after command A
succeeds:
A && B
But what if I want D
to be run only after A
, B
, C
all succeed?
Is
'A&B&C' && D
OK?
Besides, what should I do if I want to know exactly which command failed, among A
, B
and C
(as they will run many times, it will take a while if I check one by one).
Is it possible that the error info will be output to a text file automatically as soon as any command failed?
In my case, A
, B
, C
are curl
while B
is rm
, and my script is like this:
for f in *
do
curl -T server1.com
curl -T server2.com
...
rm $f
done
Try this:
A; A_EXIT=$?
B; B_EXIT=$?
C; C_EXIT=$?
if [ $A_EXIT -eq 0 -a $B_EXIT -eq 0 -a $C_EXIT ]
then
D
fi
The variables A_EXIT
, B_EXIT
and C_EXIT
tell you which, if any, of the A
, B
, C
commands failed. You can output to a file in an extra if
statement after each command, e.g.
A; A_EXIT=$?
if [ $A_EXIT -ne 0 ]
then
echo "A failed" > text_file
fi
why not store your commands in an array, and then iterate over it, exiting when one fails?
#!/bin/bash
commands=(
[0]="ls"
[1]="ls .."
[2]="ls foo"
[3]="ls /"
)
for ((i = 0; i < 4; i++ )); do
${commands[i]}
if [ $? -ne 0 ]; then
echo "${commands[i]} failed with $?"
exit
fi
done
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