I'm reading an example bash shell script:
#!/bin/bash
# This script makes a backup of my home directory.
cd /home
# This creates the archive
tar cf /var/tmp/home_franky.tar franky > /dev/null 2>&1
# First remove the old bzip2 file. Redirect errors because this generates some if the archive
# does not exist. Then create a new compressed file.
rm /var/tmp/home_franky.tar.bz2 2> /dev/null
bzip2 /var/tmp/home_franky.tar
# Copy the file to another host - we have ssh keys for making this work without intervention.
scp /var/tmp/home_franky.tar.bz2 bordeaux:/opt/backup/franky > /dev/null 2>&1
# Create a timestamp in a logfile.
date >> /home/franky/log/home_backup.log
echo backup succeeded >> /home/franky/log/home_backup.log
I'm trying to understand the use of /dev/null 2>&1
here. At first, I thought this script uses /dev/null
in order to gracefully ignore errors, without causing the script to crash (kind of like try catch exception handling in programming languages). Because I don't see how using tar to compress a directory into a tar file could possibly cause any type of errors.
Best Answer
No, this will not prevent the script from crashing. If any errors occur in the
tar
process (e.g.: permission denied, no such file or directory, ...) the script will still crash.This is because of using
> /dev/null 2>&1
will redirect all your command output (bothstdout
andstderr
) to/dev/null
, meaning no outputs are printed to the terminal.By default:
In the script, you use
> /dev/null
causing:And then
2>&1
causing: