I have a bash function to set the $PATH like this --
assign-path()
{
str=$1
# if the $PATH is empty, assign it directly.
if [ -z $PATH ]; then
PATH=$str;
# if the $PATH does not contain the substring, append it with ':'.
elif [[ $PATH != *$str* ]]; then
PATH=$PATH:$str;
fi
}
But the problem is, I have to write different function for different variables (for example, another function for $CLASSPATH like assign-classpath() etc.). I could not find a way to pass argument to the bash function so that I can access it by reference.
It would be better if I had something like --
assign( bigstr, substr )
{
if [ -z bigstr ]; then
bigstr=substr;
elif [[ bigstr != *str* ]]; then
bigstr=bigstr:substr;
fi
}
Any idea, how to achieve something like above in bash?
assign-path /abcwill not append/abcto PATH if $PATH already contains/abc/def,/abcd,/def/abcetc. Especially you can't add/binif PATH already contains/usr/bin. – miracle173 Apr 02 '14 at 05:33$PATHand negate test against your arguments like:add=/bin dir=/usr/bin ; [ -z "${dir%"$add"}" ] || dir="${dir}:${add}". In my answer I do it this way with as many arguments as you like only usingIFS=:. – mikeserv Apr 02 '14 at 06:39$PATH? and Add directory to$PATHif it’s not already there (on [SU]). – Scott - Слава Україні Jul 12 '19 at 19:22