Tom Sasson
Tom Sasson

Reputation: 1

create variables inside unix script

I am trying to create a variable in a script, based on another variable.

I just don't know what needs to be adjusted in my code, if it is possible. I am simplifying my code for your understanding, so this is not the original code.

The code goes like that:

#!/bin/csh -f

set list_names=(Albert Bela Corine David)
set Albert_house_number=1
set Bela_house_number=2
set Corine_house_number=3
set David_house_number=4

foreach name ($list_names)
  #following line does not work....
  set house_number=$($name\_house_number)
  echo $house_number
end

the desired output should be:

1
2
3
4

Thanks for your help.

Upvotes: 0

Views: 118

Answers (1)

Wintermute
Wintermute

Reputation: 44023

Unfortunately, the bashism ${!varname} is not available to us in csh, so we'll have to go the old-fashioned route using backticks and eval. csh's quoting rules are different from those of POSIX-conforming shells, so all of this is csh specific. Here we go:

set house_number = `eval echo \" \$${name}_house_number\"`
echo "$house_number"

${name} is expanded into the backticked command, so this becomes equivalent to, say,

set house_number = `eval echo \" \$Albert_house_number\"`

which then evaluates

echo " $Albert_house_number"

and because of the backticks, the output of that is then assigned to house_number.

The space before \$$ is necessary in case the value of the expanded variable has special meaning to echo (such as -n). We could not simply use echo "-n" (it wouldn't print anything), but echo " -n" is fine.1

The extra space is stripped by csh when the backtick expression is expanded. This leads us to the remaining caveat: Spaces in variable values are going to be stripped; csh's backticks do that. This means that if Albert_house_number were defined as

set Albert_house_number = "3   4"

house_number would end up with the value 3 4 (with only one space). I don't know a way to prevent this.

1 Note that in this case, the echo "$house_number" line would have to be amended as well, or it would run echo "-n" and not print anything even though house_number has the correct value.

Upvotes: 1

Related Questions