Linux Bash Script, Single Command But Multiple Lines


I have the following script I wrote by searching Google, and it backs up my Linux system to an archive:

# init

DATE=$(date +20%y%m%d)

tar -cvpzf /share/Recovery/Snapshots/$HOSTNAME_$DATE.tar.gz --exclude=/proc --exclude=/lost+found --exclude=/sys --exclude=/mnt --exclude=/media --exclude=/dev --exclude=/share/Archive /

This works, but I am wondering if I can format the script to show the command over multiple lines, something like this, so it is easy to edit later:

tar -cvpzf /share/Recovery/Snapshots/$HOSTNAME_$DATE.tar.gz 

That way it is easier to read and edit later. Is it possible to format a Bash script this way?

Best Answer

All you should need to do is add "\" at the end of each line and it should be good to go.

So yours will look like:

tar -cvpzf /share/Recovery/Snapshots/$(hostname)_$(date +%Y%m%d).tar.gz \
    --exclude=/proc \
    --exclude=/lost+found \
    --exclude=/sys \
    --exclude=/mnt \
    --exclude=/media \ 
    --exclude=/dev \
    --exclude=/share/Archive \

A Few Shortcuts

(based on your comment update for setting $HOSTNAME)


Two options to set that:



  2. Use command substitution (e.g. $(command))

    So it would look like above. That just makes the command run before using it.


Another variable avoided would be easily:

$(hostname)_$(date +%Y%m%d).tar.gz \

$ man date will have the formats for the date options, the above is YYYYmmdd

Related Question