5

I have 3 variables I'm trying to insert into an echo command that contains the string, as well.

Here is what I have:

1= "test1"
2= "test2"
3= "test3"

FileName= "WEATHERMAP"_"$1"_"STATE"_"$2"_"CITY"_"$3" 

echo $FileName

I want it to echo WEATHERMAP_test1_STATE_test2_CITY_test3
Instead I get WEATHERMAP__STATE__CITY_

I know this has something to do with the underscore, unfortunately, I need the underscore.

The only examples I have seen are putting two variables together, or it started with a variable followed by a string.

5
  • 2
    FileName="WEATHERMAP_${1}_STATE_${2}_CITY_${3}" Commented May 5, 2016 at 5:17
  • 1
    Also, Variables can also contain digits but a name starting with a digit is not allowed: source link Commented May 5, 2016 at 5:38
  • 2
    There should be no spaces preceding and following the assignment operator. Values should be assigned this way a="test" Commented May 5, 2016 at 5:43
  • shellcheck.net misses the obvious, but catches the other two errors which none of the answers so far have bothered to point out. In general, use a syntax checker before asking here about basic scripting problems. Commented May 5, 2016 at 9:12
  • (Reported a bug; github.com/koalaman/shellcheck/issues/663) Commented May 5, 2016 at 11:43

3 Answers 3

3

Don't start variable names with a number.

$ a="test1"
$ b="test2"
$ c="test3"
$ FileName="WEATHERMAP_${a}_STATE_${b}_CITY_${c}"
$ echo "$FileName"
WEATHERMAP_test1_STATE_test2_CITY_test3
$
Sign up to request clarification or add additional context in comments.

2 Comments

This is similar to what @anubhava commented, but in my lab the _ after the first variable makes everything after it one long variable.
@buzzin thats why you have to put each variable into curly brackets ${var}
0

I'm guessing you're using bash by default, in which case letters, numbers and underscores are allowed, but you can't start the variable name with a number. You can achieve by following code :-

a="test1"
b="test2"
c="test3"

FileName="WEATHERMAP"_"$a"_"STATE"_"$b"_"CITY"_"$c"
## Also, can assign as below :
## FileName="WEATHERMAP_${a}_STATE_${b}_CITY_${c}"

echo $FileName

Comments

0

The numerical variables are reserved for shell internal purposes, $0 contains script filename, $1 - first script argument, like ./script.sh first-argument, $2 - second script argument, etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.