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.



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.

  • 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

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"_
$ echo $BUILDNUMBER"_"
$ printf '%s_\n' "$BUILDNUMBER"
  • @Kevin uhm. Yes, thank you, I know. Which is why I'm quoting my variables even in this silly example where there's no reason to given that we know what the variable holds. Nevertheless, I am quoting for the printf call. I also, however, wanted to demonstrate that you can do both "$var"_ and $var"_" to get the same result. Quoting in the second case, the only instance of an unquoted variable here, would defeat the purpose since "$var_" doesn't expand correctly. – terdon Apr 11 '17 at 21:47
  • Use "$var""_" – Kevin Apr 11 '17 at 22:03
  • @Kevin why? You are quoting a string, not a variable. That adds no security, avoids no possible issues, makes absolutely no difference with the split+glob and only adds two unnecessary characters to your code. I could understand claiming that $var"_" is dangerous (it is) but an unquoted underscore has no special meaning in any shell I've heard of and certainly not in bash. If you must quote the simple string, at least use "${var}_". – terdon Apr 11 '17 at 22:53
  • Well then use "$var"_. You're the one who wanted to quote the underscore in the first place. – Kevin Apr 11 '17 at 23:14
  • 6
    I did use that. Right there in my first example – terdon Apr 11 '17 at 23:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.