0
\$\begingroup\$

A single directory should simply be backed up with the zip tool, and the time of the backup should be preserved in the file name. I have written a Posix shell script for this.

Can this script simply be converted into a .bashrc alias?

#!/bin/sh
if [ -z "$1" ]
  then
    echo "No argument supplied"
    exit
fi
fn=$(echo "backup_${1%/}_$(date +%F_%T).zip" | sed s/:/-/g)
echo "$fn"
zip -r "$fn" "$1"
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

This script is not super friendly. (Also, absent some articulated motivation for turning it into a bash alias, I would just leave it as a Bourne sh script.)

    echo "No argument supplied"
    exit

The word "argument" is true, but it's not very helpful. Instead, prompt the user to enter "an input filename" so it can be backed up. We call this a diagnostic message, one which offers a hint of "do this and you will win!" rather than just announcing "you lose!".

Exiting with status 0 here seems Bad. Prefer exit 1, so make and other callers will know that things went horribly wrong.

A common idiom would be to first assign a meaningful parameter name:

in_file="$1"

and then work with the name rather than the arg position number.

filename

fn=$(echo "backup_${1%/}_$(date +%F_%T).zip" | sed s/:/-/g)

The abbreviation is for "filename". Fine, we'll just accept that as-is.

The % percent is entirely too cryptic. It strips trailing / slash, but not e.g. trailing /readme, leaving that one intact. You didn't offer any # comments, nor review context, to motivate the "strip trailing slash" feature. Recommend you just delete it.

I feel you probably want to use $(basename "${in_file}") here. That would be a more salient concept.

As written, fn can include embedded / slashes, and it seems that would be undesirable. Using basename is an easy way to eliminate that possibility.

The sed is lovely. Consider rephrasing it as tr : -

quoting

I like the consistent use of quoting, just in case filenames contain embedded SPACE characters. Possibly you used shellcheck on this, which definitely is helpful.

\$\endgroup\$
1
  • \$\begingroup\$ Yes, I have used shellcheck for this. Thanks for your answer. \$\endgroup\$ Jan 18 at 6:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.