Check command success in bash

12,247

Solution 1

I'd do:

ok=true
if dd ...; then
  sync
else
  ok=false
fi

cp ... || ok=false

if "$ok"; then
  mformat...
fi

Solution 2

Since you are using bash just add:

set -e

to the beginning of your script and it will fail whenever any of the commands failed.

Solution 3

Try with:

dd <command>
DD_EXIT_STATUS=$?

cp <command>
CP_EXIT_STATUS=$?

if [[ DD_EXIT_STATUS -eq 0 && CP_EXIT_STATUS -eq 0 ]]; then
    format floppy disk
else
    ... other stuff ...
fi

Solution 4

You've got some of the syntax you need in your first dd command: the && means "only execute what comes next if what comes before succeeds."

The if statement takes a command (or series of commands!) and runs them, and then checks the success value at the end. So you could do:

if
    dd etc. etc. && sync &&
    cp etc. etc.
then
    format etc.
fi

Solution 5

For error proofing your commands:

execute [INVOKING-FUNCTION] [COMMAND]

execute () {
    error=$($2 2>&1 >/dev/null)

    if [ $? -ne 0 ]; then
        echo "$1: $error"
        exit 1
    fi
}

Inspired in Lean manufacturing:

Share:
12,247

Related videos on Youtube

Informancien
Author by

Informancien

Updated on September 18, 2022

Comments

  • Informancien
    Informancien almost 2 years

    I'm currently writing a small script to backup bulks of floppy disks and format them afterward for later use.

    I use dd to copy the disk's image and cp to copy all the files on the disk.

    Here are the commands I use to do so:

    # Copying disk image
    dd if="/dev/fd0" of="/path/to/backup/folder" &>/dev/null && sync
    
    # Copying disk files
    cp -R "/mnt/floppy/." "/path/to/backup/folder/" &>/dev/null
    

    After this process, the script needs to format the floppy disk. My problem is that I want my script to format the floppy disk only if both backup commands (dd and cp) were successful.

    For example, if dd couldn't copy all 1.44MB of the floppy disk because of bad blocks, then do not format the floppy disk.

    How can I test if both commands were successful (They must be tested seperatly, as I do not always backup both disk's image and files)?

    • Wildcard
      Wildcard over 6 years
      If you don't always back up both the image and the files, then how do you expect both commands to be successful?
  • Stéphane Chazelas
    Stéphane Chazelas over 7 years
    Though that would not run cp if either dd or sync failed.
  • Wildcard
    Wildcard over 6 years
  • bu5hman
    bu5hman over 6 years
    Execute is for SQ statements.
  • Alberto Salvia Novella
    Alberto Salvia Novella over 6 years
    What's a "SQ statement"?
  • bu5hman
    bu5hman over 6 years
    Typo, I meant SQL.
  • bu5hman
    bu5hman over 6 years
    Or you just intended this as a script function?
  • Alberto Salvia Novella
    Alberto Salvia Novella over 6 years
    Just as a script function, although you can port the concept to any context.