简体   繁体   中英

How to run a bash script as a command?

I have a bash script that I would like to run globally as a command. For that I moved the script to /usr/local/bin/somefile.sh .

Now I still have to call a command called somefile.sh . I would like to have an alias for this command (for example I would just like to call the script with the command sf ).

How do I do that?

There are different ways:

  • as you mentioned, use alias , man alias for details
  • create a soft link named sf to your real script
  • rename your script

And to complement answer from @Kent :

alias sf='/usr/local/bin/somefile.sh' using alias

ln -s somefile.sh /usr/local/bin/sf using soft link

mv /usr/local/bin/somefile.sh /usr/local/bin/sf using renaming

Open your .bashrc file located in ~/.bashrc . .bashrc file is read whenever you login to the system. Add the below line to the end of the file.

alias sf='/usr/local/bin/somefile.sh'

then re login or run source .bashrc

If you're on a GNU system, you could use the "alternatives" system:

dir=/usr/local/bin
sudo update-alternatives --install $dir/sf somefile $dir/somefile.sh 10

This creates 2 symbolic links:

/usr/local/bin/sf -> /etc/alternatives/somefile
/etc/alternatives/somefile -> /usr/local/bin/somefile.sh

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM