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

1
  • 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
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.

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
1
3

I'd do:

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

cp ... || ok=false

if "$ok"; then
  mformat...
fi
0
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
1
  • Though that would not run cp if either dd or sync failed. Oct 4 '16 at 14:28
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:

5
  • 1
    Execute is for SQ statements.
    – bu5hman
    Dec 29 '17 at 6:17
  • What's a "SQ statement"? 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. Jan 1 '18 at 4:12
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

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.