How to Write a Bash Shell Script and Run It
I don't want to call this a beginners guide because I feel that it is simply too awesome for that kind of language. Here I will teach mastery in the art of creating a basic shell script from scratch that uses echo to print things on the command line, modifying the permissions with chmod to make the script executable, setting the $PATH
so that it can be run like a command, and, of course, actually running it. For now this will only be tested on a Mac. However, I will be using pretty standard stuff, so a Linux or Unix machine will probably work about the same for these purposes.
Open a new terminal or console window or command line or what have you or whatever it's called these days and type nano new.sh. Actually, wait, back up. First let's make a directory to put this thing in. So maybe do something like mkdir ~/script-directory then cd ~/script-directory or whatever name. Maybe bash or bin or something like that would be better. Ok. Good. Now we're in our script directory. Make the script here with nano, or whatever text editor, just as long as it's plain text. Save and exit in nano with control + o to write out (save) and then control + x to exit.
#!/bin/bash
echo "This is an awesome bash script!"
Use chmod to Make the Script Executable
At this point the script is a script and it can be run by typing in the path to the script, so ~/script-directory/new.sh, or, since already in ~/script-directory, simply typing new.sh will do. Except, when I tried this bash told me -bash: /Users/awesome/bin/new.sh: Permission denied. Oh yeah, that's right, permissions.
Doing chmod 744 ~/script-directory/new.sh will fix this right up. This makes the file executable to the user who created the file. Try running it again.
Adding the Script Directory to the Path
Create or modify .profile in the home directory -- so nano ~/.profile -- and add:
export PATH=$PATH:/path/to/script-directory
Of course change /path/to/script-directory to the actual path to the script directory, probably something like /Users/username/script-directory. For the changes to take effect either close and reopen the console or type source ~/.profile
The script directory can be removed from the path simply by removing that line of text from .profile and restarting the console or using the source command.
Get the full path to the script directory by navigating to that directory and typing pwd -- print working directory.
Run the Script Like a Command
So now the script can be run pretty much just like a command. Type new.sh and the script will run. Just don't make the script the same name as another command. I'm not even sure what this would do.