In this example function below, I cannot figure out what certain parts mean.
if ! echo $PATH
what is "if !"?
(^|:)$1($|:)
What is
^|:
and
$|:
?
pathmunge () {
if ! echo $PATH | /bin/egrep -q "(^|:)$1($|:)" ; then
if [ "$2" = "after" ] ; then
PATH=$PATH:$1
else
PATH=$1:$PATH
fi
fi
}
# Path manipulation
if [ `id -u` = 0 ]; then
pathmunge /sbin
pathmunge /usr/sbin
pathmunge /usr/local/sbin
fi
pathmunge /usr/X11R6/bin after
unset pathmunge
As glad as we are to help, please consider reading man pages, e.g. man bash/ksh/your shell , to help yourself; those are immense sources of knowledge...!
1) man bash :
so: if ! means if NOT
2) man regex :
so (^|:)$1($|:) means $1 enclosed in : or at the begin-of-line ( ^ ) or at the end-of-line ( $ )...
The highlighted parenthesis represents how you should see that line of code. They are not intended to be included. echo $PATH output becomes the input of egrep , which is asked to find a pattern in that output of echo.
It is looking for the following pattern:
Start of string or character : + argument string + end of string or character :
By placing a ! in front of the whole expression, it turns it into if not found
Look how pathmunge is used below, as an example:
pathmunge /usr/X11R6/bin after
In English terms:
If /usr/X11R6/bin does not exist append to the path (at the end). That's the after argument.
Attention, if ! ( ... ) would run ... in a sub-shell. This is extra fork-overhead, and can have some other impact, like a ((var+=1)) will not copy back to the main shell.
Actually this patchmunge() function is in RH/CentOS 5 /etc/profile. And is risky, at least one must quote
if ! echo "$PATH" | /bin/egrep -q "(^|:)$1($|:)")
And also needs an external program /bin/egrep.
It is improved in RH/CentOS 6:
pathmunge () {
case ":${PATH}:" in
*:"$1":*)
;;
*)
if [ "$2" = "after" ] ; then
PATH=$PATH:$1
else
PATH=$1:$PATH
fi
esac
}
The functionality of pathmunge is:
it prepends the 1st argument to the PATH (if not yet exists), unless the 2nd argument is "after" where it appends the 1st argument to the PATH (if not yet exists).