Ever wanted to make yourself more efficient with a script? The following steps will show you how to set up a basic shell script to run in the terminal on OS X.

  1. Create a plain text file wherever you want and insert your shell commands. For instance, you could have a file called myscript (no extension needed) with the following contents:

    #!/bin/bash
    
    echo Hello World!
    
  2. Now, make the script executable by entering this into the OS X terminal (not your file):

    $ chmod +x path/to/myscript
    
  3. To allow running your script easily from the terminal, you have two options: create an alias or edit your PATH. First, open your .bash_profile (I prefer using nano):

    $ nano ~/.bash_profile
    
    • To add an alias to your script, add the following to your .bash_profile, replacing myalias with whatever you like:

      alias myalias='path/to/myscript'
      
    • Alternately, to edit your PATH, prepend the parent directory of your script to the PATH environment variable, in your .bash_profile:

      PATH=path/to/parent/:$PATH
      

      Note that whether your prepend or append matters, as the OS searches for commands in your PATH from left to right and goes with the first match. You can alwasy run which <command> to see which path it matched.

  4. Now, restart the terminal, or type the following to reload your .bash_profile:

    $ source ~/.bash_profile
    
  5. Finally, try it out. If you used an alias, try typing myalias in the terminal. If you edited your PATH, type the script name (myscript in our case) in the terminal. A special note about the latter: because you added the script’s parent directory to your PATH, the terminal knows to search there for your script. Consequently, you could even add more scripts to that directory and they would work too (as long as you chmod them)!


bash scripting terminal
PREV NEXT