Declare invalid bash id

I have a problem with my bash script. What I am doing is assigning variables like this.

for ((i=START;i<=END;i++) declare var$i=$(something) done 

And it works, but now I have a problem with Finnish characters like å, ä, ö. What states, says something like this

 bash:declare 'wörd' not a valid identifier 

Although it works fine if I do this

 declare var2=$(sömething) 

I can convert characters using sed, but it's better to have them, as always, so this is the last solution. So I would like to know how I can assign variables like

 var$i 

with finnish symbols. The word wörd is part of the output of my "something" command. When there are two or more words, only the word (s) that contain the character ö, ä, etc. are not assigned to a variable, therefore, if the output of the command was "something wörd", then the only thing that appears with an echo is It is something.

+5
source share
2 answers

bash simply does not allow identifiers to use characters other than AZ, az, 0-9, and _. However, the error you described is only a side effect of this limitation. declare is a command that takes a string argument that looks like an assignment operator, but the semantics are slightly different. Consider this command:

 foo () { echo "something wörd" } 

In the assignment operator, the right-hand side does not undergo word splitting, so you do not need to specify a command replacement. The following works great:

 $ word3=$(foo) $ echo "$word" something wörd 

With declare , however, command substitution undergoes word splitting, so when you write

 $ i=3 $ declare word$i=$(foo) 

it is equivalent to a team

 $ declare word3=something wörd 

which passes two names for declare to create, word3 (which gets the value) and wörd (this is an invalid name). declare word3="something wörd" will work fine; splitting of the shell word is already performed by the time declare receives an argument.

With declare , then you need to specify command substitution (or the entire string) so that all output is treated as the value for the new variable.

 $ i=3 $ declare "word$i=$(foo)" $ echo "$word3" something wörd 
+6
source

Try running the script with /bin/bash on the command line if sh (:

Instead:

 >> sh script.sh 

Try:

 >> /bin/bash script.sh 
0
source

All Articles