1

I would like to set a value via alias of it in bash, like following.

ORIGINAL_VALUE="a"
ALIAS="ORIGINAL_VALUE"
"$ALIAS"="b"  # This line does not work.
echo "value is $ORIGINAL_VALUE"

The result I expect is

value is b

Now I know it is possible to read the value of ORIGINAL_VALUE via ALIAS by

${!ALIAS}

But, unfortunately, I don't know how to set the value of ORIGINAL_VALUE via ALIAS, like "$ALIAS"="b", which does not work.

Some who has a solution or a suggestion, please tell me it. Thank you very much.

mora
  • 2,217
  • 4
  • 22
  • 32
  • 1
    `alias` is a shell keyword -- you might try to use a different term to avoid confusing folks about your meaning. – Charles Duffy Aug 20 '16 at 17:14
  • 1
    BTW, see also http://mywiki.wooledge.org/BashFAQ/006#Assigning_indirect.2Freference_variables – Charles Duffy Aug 20 '16 at 17:15
  • Thank you, Charles Duffy, for giving me a site with comprehensive instruction of reference of variable. By the way, you marked this question as duplicated. Should I delete this question? I am afraid points I offered to contributers are also deleted. – mora Aug 20 '16 at 17:47
  • 1
    There's no reason to delete it -- duplicates serve a useful purpose when, as here, they use different enough terms to pose a question to make it more likely for someone who's searching to find a hit on the terms they use. – Charles Duffy Aug 20 '16 at 17:59

3 Answers3

3

You can use declare:

ORIGINAL_VALUE="a"
ALIAS="ORIGINAL_VALUE"
declare $ALIAS="b"
echo "value is $ORIGINAL_VALUE"

Output:

value is b

Side note: If you put this into a function and want to change the value of a variable from outside the scope of the function this won't work since declare would redeclare the variable locally in that case.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • 1
    Thank you, hek2mgl. Your solution and side note was great information for me. I need to reset the original variable as global variable. So this time, solution from chepner seems to be better way. Thank you again. – mora Aug 20 '16 at 18:21
  • You are welcome. I agree that chepner's answer is a better choice if you have bash-4.3 and don't care about other shells. – hek2mgl Aug 20 '16 at 18:23
3

Use a nameref (bash 4.3 or later)

$ declare -n alias=original_value
$ original_value=a
$ alias=b
$ echo "$original_value"
b
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Nice! Never knew that *my* bash can do that. – hek2mgl Aug 20 '16 at 17:51
  • Thank you, chepner. It works in my bash. I suppose your answer is the direct answer to my question. Other answers are also great, of course and they may have advantage of compatibility. Thank you. – mora Aug 20 '16 at 18:10
0

Assuming you can trust the variables are safe:

eval $ALIAS=b
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176