简体   繁体   中英

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

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, eg

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

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.

You can get the return from the previous command by doing ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM