1

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
Bill R
  • 123
  • 4
  • 1
    I think the `>` in `if [ $# > 0 ] ; then` is not doing what you think it is. Please refer to [Comparing numbers in bash](https://stackoverflow.com/questions/18668556/comparing-numbers-in-bash). – Rfroes87 Nov 01 '20 at 20:42
  • 1
    Within single brackets `bash` interprets `>` as output redirection and creates a file named `0` in the current directory. – Cyrus Nov 01 '20 at 21:40

2 Answers2

2

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}} 
Lenna
  • 1,220
  • 6
  • 22
  • 1
    That's `u=${1:-$USER}` (note the `'-'` instead of `'='`) – David C. Rankin Nov 02 '20 at 03:52
  • 1
    Additionally the `>` with `[[...]]` isn't a numeric comparison, e.g. `"When used with [[, the < and > operators sort lexicographically using the current locale."` (~line 282 in man bash) (the `-gt` is still proper) Rest looks good. – David C. Rankin Nov 02 '20 at 03:54
  • You're right that `[[ a > b ]]` is not doing what one might think it would do, but in this case `$#` will be some number `0,1,2...100,101...` and it will be compared to `0`. Using `[[ $# > 0 ]]` will work the way OP **wants it to** but perhaps not in the **way they might expect**. – Lenna Nov 02 '20 at 04:01
  • 1
    Yes, you are safe for ASCII (and all LOCALEs I can think of), and you noted the sort, so people won't come away thinking it does something different. – David C. Rankin Nov 02 '20 at 04:02
0

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.

Bill R
  • 123
  • 4