pathmunge () { if ! echo $PATH | /bin/egrep -q "(^|:)$1($|:)" ; then PATH=$1:$PATH fi } pathmunge /sbin
Basically the function pathmunge() is used to add some string to the $PATH variable if the string is not already in the $PATH. In the code above, the line "pathmunge /sbin" is an actual call of the function.
There are several technical tips here for understanding the code.
The most compact syntax of the "if" command is
if TEST-COMMAND; then CONSEQUENT-COMMANDS; fi
- For the "if" statement, if the test command has the return status 0, then the "then" part is executed. Note this is different from some other programming languages where 0 means false.
- It is common to see the "if" statement like this "if [ ... ]". But here the test command is different. The test command might be any UNIX command that returns an exit status, and that "if" again returns an exit status of zero. In our case, the test command is
! echo $PATH | /bin/egrep -q "(^|:)$1($|:)"
This command first does the echo. Then does the egrep. And then apply the "!" operator. So if egrep is successful ( i.e, the string is found ), then "!" changes this to non-zero, and the "then" part will not be executed.
- The regular expression is "(^|:)$1($|:)". In this expression is the character "$" in "$1" a character for matching or is "$1" a symbol for the first parameter passed to the function pathmunge()? Answer: $1 is the first parameter. This is called "shell expansion".
- In the regular expression, the "^" character means to match the beginning. The second "$" means to match the end. The parentheses "()" is for a group. The character "|" is like an OR operator. So for the call in the code, the pattern will match the following. Here I use * to denote 0 or more characters:
- /sbin
- /sbin:*
- *:/sbin
- *:/sbin:*
- In the "then" part, you can have more than one command. For example, you can use
if ! echo $PATH | /bin/egrep -q "(^|:)$1($|:)" ; then echo "\$1 is " $1 PATH=$1:$PATH fi
No comments:
Post a Comment