How do I manipulate $PATH elements in shell scripts?

前端 未结 12 1187
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 04:03

Is there a idiomatic way of removing elements from PATH-like shell variables?

That is I want to take

PATH=/home/joe/bin:/usr/local/bin:/usr/bin:/bin:         


        
12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 04:35

    For deleting an element you can use sed:

    #!/bin/bash
    NEW_PATH=$(echo -n $PATH | tr ":" "\n" | sed "/foo/d" | tr "\n" ":")
    export PATH=$NEW_PATH
    

    will delete the paths that contain "foo" from the path.

    You could also use sed to insert a new line before or after a given line.

    Edit: you can remove duplicates by piping through sort and uniq:

    echo -n $PATH | tr ":" "\n" | sort | uniq -c | sed -n "/ 1 / s/.*1 \(.*\)/\1/p" | sed "/foo/d" | tr "\n" ":"
    

提交回复
热议问题