7

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 04:49

6 Answers6

4

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.

techraf
  • 5,941
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
Echoes_86
  • 752
3

I'd do:

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

cp ... || ok=false

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

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
Jander
  • 16,682
1

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:

0

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
MichaelZ
  • 101