erical
erical

Reputation: 365

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

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

Upvotes: 5

Views: 2754

Answers (4)

Rajitha Fernando
Rajitha Fernando

Reputation: 1865

conditionally do something if a command succeeded or failed (acording to this StackExchange answer)

if command ; then
    echo "Command succeeded"
else
    echo "Command failed"
fi

You can develop this simple code to execute multiple if conditions and also lets you know which command failed.

This might not be the perfect answer for question but thought it might help someone.

Upvotes: 0

Christopher Neylan
Christopher Neylan

Reputation: 8292

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

Upvotes: 1

viGeek
viGeek

Reputation: 417

You can get the return from the previous command by doing i.e

command ; echo $?

1 = failed 0 = success

In a more structured format, example:

cat /var/log/secure
  if [ $? -ne "1" ] ; then
    echo "Error" ; exit 1
  fi

Upvotes: 0

Adam Zalcman
Adam Zalcman

Reputation: 27233

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

Upvotes: 5

Related Questions