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?

1
  • Feel free to take advantage of the resources listed on the tag wiki, such as shellcheck which automatically diagnoses things like this. Commented Feb 25, 2014 at 21:22

3 Answers 3

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.
Sign up to request clarification or add additional context in comments.

1 Comment

or (( $# )), or [ -n "$1" ]. The last is slightly different, but may be more valuable in some context.
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.)

Comments

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.

2 Comments

You can still use ~ instead of $HOME for the default value.
@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. (stackoverflow.com/questions/5930671/…)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.