How to run a .sh-script from any path in an Unix t

2019-02-23 23:37发布

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 script, that has into Desktop, now change directory to Desktop and run.

Then I have another in root; now change the directory to root and run that.

My question is: How can I run any shell-script by just typing ./script from any path like we start Metasploit from any path by giving msfconsole from any path.

2条回答
Fickle 薄情
2楼-- · 2019-02-24 00:16

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 possible .bashrc) file to set PATH. Beware the 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 us 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.

查看更多
做自己的国王
3楼-- · 2019-02-24 00:25

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.

查看更多
登录 后发表回答