39

The variable BUILDNUMBER is set to value 230. I expect 230_ to be printed for the command echo $BUILDNUMBER_ but the output is empty as shown below.

# echo $BUILDNUMBER_

# echo $BUILDNUMBER
230
Kusalananda
  • 320,670
  • 36
  • 633
  • 936
Talespin_Kit
  • 557
  • 1
  • 5
  • 10

2 Answers2

55

The command echo $BUILDNUMBER_ is going to print the value of variable $BUILDNUMBER_ which is not set (underscore is a valid character for a variable name as explicitly noted by Jeff Schaller)

You just need to apply braces (curly brackets) around the variable name or use the most rigid printf tool:

echo "${BUILDNUMBER}_"
printf '%s_\n' "$BUILDNUMBER"

PS: Always quote your variables.

George Vasiliou
  • 7,803
  • 3
  • 18
  • 42
  • 1
    The documentation and the standard use the term "null" for a variable set to an empty string (as opposed to an unset variable). I took the liberty of editing. – ilkkachu Apr 11 '17 at 10:04
17

As George Vassiliou already explained, that's because you're printing the variable $BUILDNUMBER_ instead of $BUILDNUMBER. The best way to get what you want is to use ${BUILDNUMBER}_ as George explained. Here are some more options:

$ echo "$BUILDNUMBER"_
230_
$ echo $BUILDNUMBER"_"
230_
$ printf '%s_\n' "$BUILDNUMBER"
230_
terdon
  • 234,489
  • 66
  • 447
  • 667
  • We know what the variable holds, but we don't know what `$IFS` holds, so `echo $BUILDNUMBER"_"` is still wrong. Of the three, only `printf '%s_\n' "$BUILDNUMBER"` is correct if we don't know what `$BUILDNUMBER` or `$IFS` hold. – Stéphane Chazelas Jan 31 '19 at 08:05