2

I am having trouble with a very simple bash script (test.sh):

if [ $# >=1 ]
then
  backup_file=$1
else
  backup_file=~/standard.tar.bz2
fi

echo $backup_file

If I pass an argument:

test.sh myfile

I get the expected output: myfile

Otherwise, I get no output. I am expecting to see (when test.sh is executed with no arguments): ~/standard.tar.bz2

What am I doing wrong?

Michael Goldshteyn
  • 71,784
  • 24
  • 131
  • 181
  • Feel free to take advantage of the resources listed on the [tag wiki](http://stackoverflow.com/tags/bash/info), such as [shellcheck](http://www.shellcheck.net) which automatically diagnoses things like this. – that other guy Feb 25 '14 at 21:22

3 Answers3

4

This condition evaluation is the problem:

[ $# >=1 ]

Change this to:

[ $# -ge 1 ]

OR else in BASH:

[[ $# -ge 1 ]]

OR:

(( $# ))
  • [...] and [[...]] don't allow >= as an operator
  • You need a space after operators.
chepner
  • 497,756
  • 71
  • 530
  • 681
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    or `(( $# ))`, or `[ -n "$1" ]`. The last is slightly different, but may be more valuable in some context. – kojiro Feb 25 '14 at 20:53
3

If you're using mathematical operators, use it in the correct context. Instead of saying:

if [ $# >=1 ]

say

if (( $# >=1 ))

(And you don't have to worry about spaces around the operators, or lack thereof.)

devnull
  • 118,548
  • 33
  • 236
  • 227
3

Others have addressed the immediate syntactical problem, but a completely different way to write this would be to take advantage of parameter expansion to use a default value:

backup_file="${1:-$HOME/standard.tar.bz2}"

This will replace backup_file with the value in $1 if and only if it exists.

kojiro
  • 74,557
  • 19
  • 143
  • 201
  • 1
    You can still use `~` instead of `$HOME` for the default value. – chepner Feb 25 '14 at 20:59
  • @chepner right, but I actually prefer HOME in scripts, because ~ does some other expansions that are probably not desirable (even if they're unlikely to happen by accident). To each his own. (http://stackoverflow.com/questions/5930671/why-use-home-over-tilde-in-a-shell-script) – kojiro Feb 25 '14 at 21:02