Bill R
Bill R

Reputation: 123

Stumped: this script does not work as expected?

I'm stumped when writing a simple script.

Essentially the $u variable is does not take u=$USER. Here's the code:

#!/bin/bash

if [ $# > 0 ] ; then
    u=$1
else
    u=$USER
fi
echo $u

Upvotes: 1

Views: 55

Answers (2)

Lenna
Lenna

Reputation: 1280

The fix

You have 2 equally viable options:

  1. Use -gt
if [ $# -gt 0 ]
  1. Use double brackets [[ (Does a lexicographic comparison but will work for this case)
if [[ $# > 0 ]]

Why?

When you did if [ $# > 0 ] the > was treated like an output redirection command similar to echo "foo" > file.txt. You might notice you have created a file named 0 someplace after executing:

if [ $# > 0 ]

When deciding between using [...] or [[...]] many find the answer is to use double brackets

Getting fancy

Now if what you'd really like to do is write a script that gives a default value to the u variable if none is provided by the first argument I would recommend using a neat bash syntax trick for implementing default values

u=${1:-${USER}} 

Upvotes: 2

Bill R
Bill R

Reputation: 123

I believe I found the answer using double brackets

#!/bin/bash

if [[ $# > 0 ]] ; then
    u=$1
else
    u=${USER}
fi
echo $u

Not sure I fully understand why it failed with single brackets.

Upvotes: 0

Related Questions