Bash variable substitution of variable followed by underscore

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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_


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments