I need to change variable name every time I ran script. Lets say I have a variable

echo "Value is : $a"

and it will print

Value is foo

But in same script i am changing the variable value


And if i run the script again it should print

Value is bar

Can we achieve that in unix?

  • Have you tried it? What happened? – roaima Feb 1 at 7:19

The line $a="bar" ought to give you an error message saying

bash: foo=bar: command not found

To set a to the string bar, use a="bar". Notice that $a is the value of the variable a, and that $a="bar" is nonsensical.

If you want to change the value each time you run the script, you can do two things (at least).

  1. Make a an environment variable. This mean that you set a outside of the script and export it:

    export a="bar"

    Then you run your script as usual (it would need to be modified to not overwrite the value of a inherited from the environment first). You could also use

    a="bar" ./myscript.sh

    to set the variable for the script only (i.e., not making it a variable in the calling shell).

  2. Make the script take the value from the command line, so that you call the script like

    ./myscript.sh "bar"

    The script would then do


    to set the value of a from the command line argument. Here, $1 means "the first command line argument".

Whichever way you go about doing this, you may also want to check that the value "$a" is sane (i.e. contains valid data) before using it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.