Check command success in bash
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:
Related videos on Youtube
Informancien
Updated on September 18, 2022Comments
-
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 andcp
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
andcp
) 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 over 6 yearsIf 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 over 7 yearsThough that would not run
cp
if eitherdd
orsync
failed. -
Wildcard over 6 years
-
bu5hman over 6 yearsExecute is for SQ statements.
-
Alberto Salvia Novella over 6 yearsWhat's a "SQ statement"?
-
bu5hman over 6 yearsTypo, I meant SQL.
-
bu5hman over 6 yearsOr you just intended this as a script function?
-
Alberto Salvia Novella over 6 yearsJust as a script function, although you can port the concept to any context.