I see that you're using quotes to avoid the problem the underscore getting used as part of the variable name. So while $1
is a positional paramater, $1_
is a variable that you have not set in your script. You can avoid this issue by using curly braces, like ${1}
. Anything inside the braces is part of the variable name, so ${1}_
works. This notation would be preferable to $1"_"
which leaves a user-provided variable outside of quotes. (Of course, "$1"_
would do the job as wel.)
Also, it's probably safer to set the filename in a variable, then use that for all your needs:
#!/bin/bash
if [ -z "$1" ]; then
echo "Help : To compress file use argument with directory"
exit 0
fi
filename="${1}_$(date '+%F').tar.bz2"
if [ -e "$filename" ]; then
echo "WARNING: file exists: $filename" >&2
else
tar -cvjSf "$filename" "$@"
fi
Changes:
- you need spaces around your square brackets in an
if
condition,
- while you can test for equivalence to a null string,
-z
is cleaner, though you could also test for [ $# -eq 0 ]
, counting the parameters provided,
- using
$filename
makes sure that your test and your tar
will always use the same name, even if the script runs over midnight, and is way more readable,
- variables should always be quoted.
Also, are you sure about the -S
option for tar? On my system, that option extracts sparse files, and is only useful in conjunction with -x
.
ALSO, I should note that as I've rewritten it, there's nothing in this script which is specific to bash, and it should be portable to POSIX shells as well (ash/dash/etc). Bash is great, but it's not universal, and if through your learning journey you can learn both, it will give you useful skills across multiple operating systems and environments.