How to run a .sh-script from any path in a terminal?

后端 未结 2 1922
小蘑菇
小蘑菇 2021-01-04 09:28

I know how to run the script I created. But it is a matter of pain that I need to change directory through terminal and run my scripts. I need to run the slowloris

相关标签:
2条回答
  • 2021-01-04 09:37

    One option is simply to type the path to the script:

    ~/Desktop/script
    

    This works fine, but gets a bit unwieldy.

    This is what the PATH environment variable is for. And it is what $HOME/bin is for.

    1. Create yourself a directory $HOME/bin. Put all your executable scripts in it (make them executable with chmod +x script if need be††). This way, there's one place to look for the scripts you want to run.
    2. Add $HOME/bin to your PATH. I put mine at the front: PATH="$HOME/bin:$PATH, but you could put it at the back if you prefer.
    3. Update your .profile or .bash_profile (or possibly .bashrc) file to set PATH. Beware of a continually growing PATH, though.

    As tripleee noted, once the command is installed in a directory on PATH, you no longer type ./script, but just script. This is exactly like you type ls and not /bin/ls, etc. Once the program is installed in a directory on your PATH, it is (for many purposes) indistinguishable from a system-provided command.

    I have about 500 scripts and programs in my $HOME/bin directory.

    Note that this doesn't require any special privileges. If you have administrator access to your machine and you think other users might find your commands useful, then you could install the scripts/programs in one of the system-provided directories on your PATH. However, it is usually best not to add programs to any of:

    • /bin
    • /usr/bin
    • /sbin
    • /usr/sbin

    There is often/usually /usr/local/bin which is a suitable place for widely used commands not provided by the system.


    †† It would be better to use chmod a+x,go-w script; your scripts should not be writable by other people. You could even simply use chmod 555 script or chmod 755 script. I tend to keep my scripts non-writable. That way, I have to go through a formal change process with the version control system. It means there's less danger of uncontrolled changes.

    0 讨论(0)
  • 2021-01-04 09:45

    You have to copy or link the script into a directory that is on the $PATH. Usually /usr/bin and /usr/local/bin/ are on the path so these are good locations to link or copy the script to.

    ln -s /path/to/your/script /usr/local/bin
    

    If you are not root you will either need to sudo that command or run it as the root user.

    0 讨论(0)
提交回复
热议问题