Use Export Command To Help Linux Find Your Scripts
September 25, 2009
linuxbashscriptsYou compiled and installed a linux binary or made a nifty script but you don’t want to mess the server bin tree. So you placed it in an isolated folder like so:
Level: Beginner, Intermediate
Yeah your a rockstar!
/usr/local/myscripts/really/great/work/bin/myutility
You go on with business as usual. But soon you got tired of typing the whole path or changing folders every time you need the app. You could simplify your life by making a symbolic link(shortcut) or a wrapper script and place it on a more convenient path like /bin or /usr/bin. But you realize that would be defeating your original intent. what do you do?
Simple. Do what experts do. Use “export” to modify the PATH environment variable.
export: export [-nf] [name[=value] …] or export -p
NAMEs are marked for automatic export to the environment of subsequently executed commands. If the -f option is given, the NAMEs refer to functions. If no NAMEs are given, or if `-p’ is given, a list of all names that are exported in this shell is printed. An argument of `-n’ says to remove the export property from subsequent NAMEs. An argument of `–‘ disables further option processing.
To get an idea, try this command on the console:
/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
The above value is a typical “root” PATH for a fresh text-only CentOS installation – so don’t fret if you got something different. This will grow in time the more you install applications. Anyway, back to business, now you want to add your “incredible” scripts. Run the ff:
Done, now see if Linux can find your script or binary.
/usr/local/myscripts/really/great/work/bin/myutility
Success! Now test your script.
If your script throws an error, you may need to work on it. It may be using hard coded relative paths. Sometimes using absolute paths can do the trick.
Yahoo! It works! Now lets take it a bit further, lets configure your system so you don’t need to keep typing the export-PATH command. Open the ~/.bash_profile file in your favorite text editor.
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/bin
export PATH
unset USERNAME
Note the tilde(~) symbol, this is just shorthand for your home folder. Lets say your username is iamgenius, that should translate to /home/iamgenius/.bash_profile
Same as what you did earlier, append your script folder to the PATH construct, as shown below
Now your done, the next time you login, the new “PATH” should kick in.
Congratulations! Now go play with your scripts!