0

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.

3

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Wintermute, that is a perfect explanation and I learnt a lot!

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.