Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run a command only after some other commands have run successfully?

Tags:

linux

bash

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
like image 916
erical Avatar asked Dec 06 '11 16:12

erical


2 Answers

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
like image 152
Adam Zalcman Avatar answered Nov 15 '22 12:11

Adam Zalcman


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
like image 27
Christopher Neylan Avatar answered Nov 15 '22 12:11

Christopher Neylan