0

When I use export command at command prompt, it works as expected. But it does not work from shell script.

[root@server shantanu]# export myip=10 [root@server shantanu]# echo $myip 10 [root@server shantanu]# vi myip.sh #!/bin/sh export myipadd=10 [root@server shantanu]# sh -xv myip.sh #!/bin/sh export myipadd=10 + export myipadd=10 + myipadd=10 [root@server shantanu]# echo $myipadd 

I want to make the variable available to the same script next time when it runs. In other words I am looking for some way to memorize the variable value.

2 Answers 2

1

Execute export command from the command line make the environment variables only take effect in the current session. Add it to your shell startup files for permanent.

For example, with bash:

echo "export myipadd=10" >> ~/.bash_profile (for only root) echo "export myipadd=10" >> /etc/profile (for all users) 
7
  • Thanks. Next time the myipadd will change to 12. How do I update profile? Or can I simply add it twice and profile will read the last entry for myipadd ? Is there any other way to achieve this? Commented Nov 14, 2011 at 7:50
  • It did not work on my centOS box. I am getting blank line returned. Commented Nov 14, 2011 at 7:57
  • You can use sed to change it, for e.g: sed -i 's/export myipadd=10/export myipadd=12/' /etc/profile Commented Nov 14, 2011 at 7:58
  • Make it take effect with source /etc/profile or just logout and login back. Commented Nov 14, 2011 at 8:02
  • Or this, much cleaner to me: echo "export myipadd=<your_ip_add>" > ~/.myipadd and then add the line source ~/.myipadd to either ~/.bash_profile or /etc/profile. That way you don't need to fool with SED on your profile script (could be dangerous =). Commented Nov 14, 2011 at 8:33
2

If you need to export your variable within a shell script and make it available to other scripts, you need to use the source command.

$ cat test.sh export MY_VAR="hello" $ source test.sh $ echo $MY_VAR hello 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.