Reputation: 123
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
Reputation: 1280
You have 2 equally viable options:
-gt
if [ $# -gt 0 ]
[[
(Does a lexicographic comparison but will work for this case)if [[ $# > 0 ]]
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
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
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