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)?

  • If you don't always back up both the image and the files, then how do you expect both commands to be successful? – Wildcard Dec 29 '17 at 4:49

I'd do:

if dd ...; then

cp ... || ok=false

if "$ok"; then
| improve this answer | |

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.

| improve this answer | |

Try with:

dd <command>

cp <command>

if [[ DD_EXIT_STATUS -eq 0 && CP_EXIT_STATUS -eq 0 ]]; then
    format floppy disk
    ... other stuff ...
| improve this answer | |

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:

    dd etc. etc. && sync &&
    cp etc. etc.
    format etc.
| improve this answer | |
  • Though that would not run cp if either dd or sync failed. – Stéphane Chazelas Oct 4 '16 at 14:28

A one-liner test would be

command_to_check && command_to_follow_if_previous_one_succeeds

You can also use the following one-liner if you want to proceed only if previous command fails.

command_to_check || command_to_follow_if_previous_one_fails
| improve this answer | |

For error proofing your commands:


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

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

Inspired in Lean manufacturing:

| improve this answer | |
  • 1
    Execute is for SQ statements. – bu5hman Dec 29 '17 at 6:17
  • What's a "SQ statement"? – Alberto Salvia Novella Dec 30 '17 at 10:33
  • Typo, I meant SQL. – bu5hman Dec 30 '17 at 12:44
  • Or you just intended this as a script function? – bu5hman Dec 30 '17 at 12:50
  • Just as a script function, although you can port the concept to any context. – Alberto Salvia Novella Jan 1 '18 at 4:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.