Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

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)
share|improve this answer
    
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? –  shantanuo Nov 14 '11 at 7:50
    
It did not work on my centOS box. I am getting blank line returned. –  shantanuo Nov 14 '11 at 7:57
    
You can use sed to change it, for e.g: sed -i 's/export myipadd=10/export myipadd=12/' /etc/profile –  quanta Nov 14 '11 at 7:58
    
Make it take effect with source /etc/profile or just logout and login back. –  quanta Nov 14 '11 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 =). –  d34dh0r53 Nov 14 '11 at 8:33
show 2 more comments

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
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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