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

In bash, I know what I should use &&if I want the command to be Brun only after the command is executed A:

A && B

But what if I want to Dstart only after A, Bis Ceverything successful? Is an

 'A&B&C' && D

Ok

Besides, what should I do if I want to know exactly which command was unsuccessful, among A, Band C(since they will be executed many times, it will take some time if I check one by one).

Is it possible that error information will be automatically output to a text file as soon as any command is executed?

In my case A, B, Cthey are curl, and B- rmand my script is as follows:

for f in * 
do 
    curl -T server1.com
    curl -T server2.com
    ...
    rm $f
done
+5
source share
3 answers

Try the following:

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

Variables A_EXIT, B_EXITand C_EXITtell you which commands when executing commands A, B, Cwere not fulfilled. You can output the file to an additional statement ifafter each command, for example.

A; A_EXIT=$?
if [ $A_EXIT -ne 0 ]
then
  echo "A failed" > text_file
fi
+5
source

why not store your commands in an array, and then iterate over it, exit 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
+1
source

, i.e

; echo $?

1 = 0 =

, :

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

All Articles