How do I manipulate $PATH elements in shell scripts?

前端 未结 12 1102
伪装坚强ぢ
伪装坚强ぢ 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:47

    The first thing to pop into my head to change just part of a string is a sed substitution.

    example: if echo $PATH => "/usr/pkg/bin:/usr/bin:/bin:/usr/pkg/games:/usr/pkg/X11R6/bin" then to change "/usr/bin" to "/usr/local/bin" could be done like this:

    ## produces standard output file

    ## the "=" character is used instead of slash ("/") since that would be messy, # alternative quoting character should be unlikely in PATH

    ## the path separater character ":" is both removed and re-added here, # might want an extra colon after the last path

    echo $PATH | sed '=/usr/bin:=/usr/local/bin:='

    This solution replaces an entire path-element so might be redundant if new-element is similar.

    If the new PATH'-s aren't dynamic but always within some constant set you could save those in a variable and assign as needed:

    PATH=$TEMP_PATH_1; # commands ... ; \n PATH=$TEMP_PATH_2; # commands etc... ;

    Might not be what you were thinking. some of the relevant commands on bash/unix would be:

    pushd popd cd ls # maybe l -1A for single column; find grep which # could confirm that file is where you think it came from; env type

    ..and all that and more have some bearing on PATH or directories in general. The text altering part could be done any number of ways!

    Whatever solution chosen would have 4 parts:

    1) fetch the path as it is 2) decode the path to find the part needing changes 3) determing what changes are needed/integrating those changes 4) validation/final integration/setting the variable

提交回复
热议问题