d) Pattern Matching, Environment Variables, Shell Scripts, and Control
Pattern Matching
Filename substitution
Environment Variables
In the Linux shell a variable is a named object that contains data and which can be used by programs and commands. Environment variables provides a simple way to share configuration settings between multiple applications and processes in Linux. For example the value of an environmental variable can be the default editor that should be used, which can then be used by command to invoke the correct editor when necessary.
Â
Predefined Environment Variables | |
Variable | Value |
---|---|
| path to the home directory of the current user. |
PWD | path to your working directory. |
OLDPWD | path to your previous working directory. |
SHELL | name of the running, interactive shell, e.g., bash |
TERM | name of the running terminal, e.g., xterm |
PAGER | path to the program used to list the contents of files, e.g., /bin/less . |
EDITOR | Â path to the program used for editing files, e.g., /usr/bin/nano |
To use an environment variable precede its name with a '$' character. We can display all define environment variables with printenv, and set values with export.
Using environment variables
-bash-4.1$ echo $PWD /usr/researchcomp/elecclust/abs4 -bash-4.1$ export MYVAR="My variable" -bash-4.1$ echo $MYVAR My variable -bash-4.1$ export MYVAR="My current directory is ${PWD}" -bash-4.1$ echo $MYVAR My current directory is /usr/researchcomp/elecclust/abs4 -bash-4.1$
Shell Scripts
Shell scripts are files which contain shell commands. You run the script by typing its filename. Things to note:
- the first line of the file should contain the string "#!/bin.bash". This informs the shell which program to run the script
- consider adding execute permission to the file to allow easy execution
- create a directory in your home directory to place all your scripts and add the directory path to your PATH variable
Scripts
-bash-4.1$ cat simple #!/bin/bash echo "I am a very simple script" -bash-4.1$ sh simple I am a very simple script -bash-4.1$ chmod u+x simple -bash-4.1$ ls -l simple -rwxr--r-- 1 abs4 csrv 46 Sep 11 12:28 simple -bash-4.1$ ./simple I am a very simple script -bash-4.1$ chmod u+x simple -bash-4.1$ ls -l simple -rwxr--r-- 1 abs4 csrv 46 Sep 11 12:28 simple -bash-4.1$ ./simple I am a very simple script -bash-4.1$ pwd /usr/researchcomp/elecclust/abs4/scripts -bash-4.1$ simple -bash: simple: command not found -bash-4.1$ export PATH="${PATH}:${HOME}/scripts" -bash-4.1$ simple I am a very simple script -bash-4.1$
Â
Control
Â