我有一个bash函数来设置$PATH这样-
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
}
但是问题是,我必须为不同的变量编写不同的函数(例如,为$CLASSPATHlike assign-classpath()等编写另一个函数)。我找不到将参数传递给bash函数的方法,这样我就可以通过引用来访问它。
如果我有类似的东西会更好-
assign( bigstr, substr )
{
if [ -z bigstr ]; then
bigstr=substr;
elif [[ bigstr != *str* ]]; then
bigstr=bigstr:substr;
fi
}
任何想法,如何在bash中实现上述效果?
assign-path /abc不会追加/abc到PATH如果$ PATH中已经包含/abc/def,/abcd,/def/abc等等。特别是你不能添加/bin如果PATH已包含/usr/bin。
$PATH并否定测试,例如:add=/bin dir=/usr/bin ; [ -z "${dir%"$add"}" ] || dir="${dir}:${add}"。在我的回答中,我只用来使用尽可能多的参数来执行此操作IFS=:。