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.

shantanuo
  • 3,579
  • 8
  • 49
  • 66

2 Answers2

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
Khaled
  • 36,533
  • 8
  • 72
  • 99
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)
quanta
  • 51,413
  • 19
  • 159
  • 217
  • 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 07:50
  • It did not work on my centOS box. I am getting blank line returned. – shantanuo Nov 14 '11 at 07: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 07:58
  • Make it take effect with `source /etc/profile` or just logout and login back. – quanta Nov 14 '11 at 08:02
  • Or this, much cleaner to me: `echo "export myipadd=" > ~/.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 08:33
  • echo "export myipadd=199" > ~/.myipadd ; source /etc/profile # this works as expected at command prompt but the same line does not work if it is part of shell script! – shantanuo Nov 14 '11 at 10:56
  • You must add `source ~/.myipadd` to `~/.bash_profile`. – quanta Nov 14 '11 at 11:00