Help - Search - Members - Calendar
Full Version: Bash script (question)
Linuxhelp > Support > Programming in Linux
kimball
Hello, I have some experience with shell scripting but am stumped on this one thing. How to declare variables in a separate file and have them called in a script. So for example, a user can edit the variables, but is unable to see the script they are being used in. Any help appreciated.
Hemant
There is a simple thing... whenever you execute a shell script, then that shell script is executed in a new shell and after your shell script terminates that shell is also terminated... and that is the reason why, variables declared in a particular shell script can't be accessed like that.

But there is a way to get around this problem. For example
CODE
#!/bin/bash
export rocks="Metallica"
export sucks="Windows"


if you execute this shell script, like this
CODE
$ chmod +x test.sh
$ ./test.sh
$ echo $rocks
 <<you will get an empty line>>


However if you do something like this
CODE
$ . ./test.sh
$ echo $rocks
Metallica
$ echo $sucks
Windows


So when you prefix . , then the shell script will be executed in the current shell. So you should make sure that you execute both you shell scripts by using ". ./<name>"
kimball
Neat, so many ways to do it. I came up with my own way by looking at some other sh scripts out there.
A command called include.
So...
File in /home/user is name config
CODE
#########
# Variables #
#########

var1="text"


Then you have a script in /bin owned by root called script1
This is inside the script
CODE
###################
# Load vars using include  #
###################

. $HOME/config
# or (don't use comment on second one)
# . ~/config
# test the var
echo "Your variable is $var1"


Now test it out by going in terminal:
CODE
[root@linux] $ cd /bin
[root@linux] $ chmod 755 (give access to everyone to read and execute)
[root@linux] $ su username
-----------you should see the following output if it was successful
[user@linux] $ script1
Your variable is text


An example of an include can be seen in your home directory in the file .bash_profile (maybe different for others)
There the script looks for a file using the if [-f . ~/filename ]; then command to load variables and aliases.
Hope this can be of help to others as it was to me and thanks for the quick reply.
Hemant
Cool man.... thanx for the extra bit of knowledge...
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2017 Invision Power Services, Inc.