How do I execute command line scripts?

Solution 1:

The terminal underpinnings in OS X are the same as those used in Linux. What you are specifically looking for is commonly referred to as "Shell Scripting".

The default shell when you open Terminal.app (located in /Applications/Utilties) is the bash shell.

OS X has had a built-in shell handler accessible via Finder and other applications via the .command extension, though frustratingly not via the .sh extension. However, setting the script up to run via the Finder is even more complicated still.

  1. Create a simple shell script, like your example I've made a Hello World application:
#!/bin/bash
echo "Hello World"
  1. Save this file as HelloWorld.command.

  2. Give this file permission to be executed. chmod u+x HelloWorld.command should do that.

  3. Open the directory where you saved this file in Finder. Then double click on the HelloWorld.command file.

This will open up a terminal and execute the script, the output on my computer is the following:

$ /Users/jason/Applications/HelloWorld.command ; exit;
Hello World
logout

[Process completed]

The alternative way of executing this file is while still in the Terminal yourself, simply issue ./HelloWorld.command assuming you're in the same directory as the file.

Doing so will result in much simpler output:

jason-mac Applications $ ./HelloWorld.command
Hello World
jason-mac Applications $

You've just created and executed a shell script in OS X!

Solution 2:

The equivalent of the Console or Command Prompt in Windows is the Terminal app located in /Applications/Utilities/

The equivalent of DOS (or whatever they're calling it these days) is "bash"

The equivalent of a batch file (.bat) in Windows is a shell script (.sh)

Just do a Google search for "bash" "reference" and you'll figure the rest out. I would also recommend buying the Bash Cookbook (O'Reilly).

Specifically, this would be what you would type into a terminal window to get your "hello world" script:

To create the file:

    echo "echo hello world" > file.sh

To change permissions to make the file executable:

    chmod 755 file.sh

To run the script:

    ./file.sh

If you want to be able to double-click it from the Finder, right-click (or control-click) on the file and select Get Info, then under Open With, select the Terminal app. Or you could use the .command extension instead of the .sh extension.