使用bash判断PATH中是否存在某个路径

来源:互联网 发布:linux 复制 粘贴 编辑:程序博客网 时间:2024/04/29 20:49

在source设置环境变量的时候,有些时候可能会设置两次,导致增加系统的路径搜索时间,或者让自己看环境变量的时候搞得怪不爽的。

为了解决这个问题,我们可以在设置相应的环境变量之前,先判断一下是否已经设置过,如果设置过,那就不要在设置了,如果没有设置呢,当然你就可以设置下啦。


我用一个函数来判断参数2的字符串是否存在与参数1中

function isexist(){    source_str=$1    test_str=$2        strings=$(echo $source_str | sed 's/:/ /g')    for str in $strings    do          if [ $test_str = $str ]; then            return 0        fi      done    return 1}

所以我们可以用一个判断来测试下这个函数就行了,

举个例子使用下这个函数,

我想设置/opt/mpich/3.0.4/bin这个目录到环境变量PATH中。可以这样做


if isexist $PATH /opt/mpich/3.0.4/bin; then   echo "no need to set it ..."else   export PATH=/opt/mpich/3.0.4/bin:$PATHfi

OK 了,测试下吧。



原创粉丝点击