Ubuntu – How can you create a command with a Bash file

bashcommand line

I created a .sh (or bash) file and I would like to make a command in GNOME-Terminal for the file. I know you run a .sh file by:

./file.sh

After you compile it, I also know all the command are stored in /bin/bash. But I can't seem to figure out how I can create a command that I can call when I am in any directory in the terminal, something like:

abc

would run abc.h, etc. Any suggestions?

Best Answer

Although Radu's answer is absolutely correct, I feel like it's a bit incomplete for the beginner that does not know the location of certain files, so here's a step-by-step on the second method (using ~/bin). If you would like to store the files somewhere else than ~/bin, follow step 1, otherwise, ignore it and keep in mind you'll be using ~/bin as your scripts folders.

  1. Open a terminal and run the following:

    nano .profile
    

    You should see, at the end of the file:

    # set PATH so it includes user's private bin if it exists
    if [ -d "$HOME/bin" ] ; then
        PATH="$HOME/bin:$PATH"
    fi
    

    If you don't see it, try using nano .bash_profile instead. Keep in mind you should be at ~/, that is, /home/YOUR_USERNAME

    This tells bash where user's scripts are. The default is /home/YOUR_USERNAME/bin which is "abbreviated" as $HOME/bin or ~/bin. You can then change it to any folder you'd like to store your scripts in. Mine is ~/.bin -- the same as the original, but hidden.

  2. If you already issued chmod +x script.sh just move your scripts to the folder in which you're going to store them - create it if it doesn't exist. Inside that folder, if you store your scripts as file.sh you'll have to run file.sh everytime, so store them as file -- no extensions.

Related Question