How do you avoid over-populating the PATH Environment Variable in Windows?

前端 未结 12 1010
慢半拍i
慢半拍i 2020-11-30 16:26

I would like to know what are the approaches that you use to manage the executables in your system. For example I have almost everything accessible through the command line,

12条回答
  •  粉色の甜心
    2020-11-30 17:18

    One way I can think of is to use other environment variables to store partial paths; for example, if you have

    C:\this_is_a\long_path\that_appears\in_multiple_places\subdir1;
    C:\this_is_a\long_path\that_appears\in_multiple_places\subdir2;
    

    then you can create a new environment variable such as

    SET P1=C:\this_is_a\long_path\that_appears\in_multiple_places
    

    after which your original paths become

    %P1%\subdir1;
    %P1%\subdir2;
    

    EDIT: Another option is to create a bin directory that holds .bat files that point to the appropriate .exe files.

    EDIT 2: Ben Voigt's comment to another answer mentions that using other environment variables as suggested might not reduce the length of %PATH% because they would be expanded prior to being stored. This may be true and I have not tested for it. Another option though is to use 8dot3 forms for longer directory names, for example C:\Program Files is typically equivalent to C:\PROGRA~1. You can use dir /x to see the shorter names.

    EDIT 3: This simple test leads me to believe Ben Voigt is right.

    set test1=hello
    set test2=%test1%hello
    set test1=bye
    echo %test2%
    

    At the end of this, you see output hellohello rather than byehello.

    EDIT 4: In case you decide to use batch files to eliminate certain paths from %PATH%, you might be concerned about how to pass on arguments from your batch file to your executable such that the process is transparent (i.e., you won't notice any difference between calling the batch file and calling the executable). I don't have a whole lot of experience writing batch files, but this seems to work fine.

    @echo off
    
    rem This batch file points to an executable of the same name
    rem that is located in another directory. Specify the directory
    rem here:
    
    set actualdir=c:\this_is\an_example_path
    
    rem You do not need to change anything that follows.
    
    set actualfile=%0
    set args=%1
    :beginloop
    if "%1" == "" goto endloop
    shift
    set args=%args% %1
    goto beginloop
    :endloop
    %actualdir%\%actualfile% %args%
    

    As a general rule, you should be careful about running batch files from the internet, since you can do all sorts of things with batch files such as formatting your hard drive. If you don't trust the code above (which I wrote), you can test it by replacing the line

    %actualdir%\%actualfile% %args%
    

    with

    echo %actualdir%\%actualfile% %args%
    

    Ideally you should know exactly what every line does before you run it.

提交回复
热议问题