tags:

views:

346

answers:

2

I get the name of a variable from the script user as the first argument and I echo the value of said variable back to the console:

#!/bin/bash
variablename=$1
echo "The value of $variablename is: " ${!variablename}

This works great!

What I can't get to work is if I want to change that variable into the value of the second argument from the user. An example with a syntax error is:

#!/bin/bash
variablename=$1
echo "The value of $variablename is: " ${!variablename}
echo "I will now try to change the value into $2."
(!variablename}=$2
# The above line generates: {!variablename}=2: command not found

In other words: If it is possible, how do I get a variable name from the user and both read (already solved) and write to said variable?

+3  A: 

I had a flash all of a sudden, minutes after asking for help, and I think I have a solution:

#!/bin/bash
variablename=$1
echo "The value of $variablename is: " ${!variablename}
echo "I will now try to change the value into $2."
eval "$variablename=$2"
echo "Success! $variablename now has the value ${!variablename}!"

It works. Is there a better way?

DeletedAccount
No, eval is the correct way to go. You might need to worry about blanks in $2, though - and single quotes and double quotes and backslashes.
Jonathan Leffler
Thanks for asserting me I'm on the right way. I'll do some parameter validation if I create something of any re-usability value. At the moment I'm mostly messing around trying to understand Bash more in-depth. :-)
DeletedAccount
+2  A: 

Your solution will work but the variable will only have that value within your script. It won't affect the "calling" application's variable.

When you run a script or program it spawns a new shell with a copy of the environment. This is by design so your script doesn't modify things like PATH.

If you want your script to be able to modify environment variables for the calling shell you need to either "source scriptname" or ". scriptname". This is how .bashrc works.

Andy
Thanks for the additional information! "source scriptname" worked fine for this. Could you elaborate a bit on ".scriptname" as I didn't understand that approach?
DeletedAccount
source scriptname is essentially the same, but it's bash specific using the dot instead of source is posix compatible
Johannes Schaub - litb
The syntax is ". scriptname", not ".scriptname". The dot command is synonymous with the source command.
converter42
libt: Ah! tnek.knowledge++converter42: Thanks for fixing that syntax error!
DeletedAccount