Terminal 101: Variables in Bash Scripting
Posted 10/15/2012 at 10:56am
| by Cory Bohon
Every Monday, we'll show you how to do something new and simple with Apple's built-in command line application. You don't need any fancy software, or a knowledge of coding to do any of these. All you need is a keyboard to type 'em out!
Last week, we introduced you to the world of Bash (or Shell) scripting and how it can benefit you by letting you stack together Terminal commands and run them at one time. This week, we’re going to take that one step further by showing you how to integrate variables and user input into the shell scripts. Continue reading to learn how it’s done.
Using Variables

In writing the bash scripts, you can utilize variables to store a piece of data (number or text) that can be used throughout the entire bash script. For instance, if you wanted to write a script to log into FTP on a remote computer, we might want to use a variable for the username, password, and initial login directory.
We’ll use the following script to do just that:
USERNAME=user
PASSWORD=sekrit
DESTINATION_FOLDER=/
echo Logging in
ftp "$USERNAME":"$PASSWORD"@serveraddress/$DESTINATION_FOLDER
USERNAME, PASSWORD, and DESTINATION_FOLDER are all variables. You create them by using the syntax on lines 1-3. The name on the left-hand side of the equal sign is the variable name, and the value of the variable is on the right-hand side. To use the variable in the command, place a $ sign in front of the variable like $USERNAME, $PASSWORD, and $DESTINATION_FOLDER. Replace “serveraddress” with the address of your FTP server.

When you run the command, you will see the “Logging in” text echoed to the command line, and then the ftp command will run, logging you into your FTP server.
Note that if you use a “@” character in your FTP password, then you may have problems signing in using the single-FTP command method used in this script.
Requesting User Input

Above, you can see how variables are created and used in the actual script, but these variables cannot change without editing the script. Another way to create a variable is by capturing user input into the terminal in a variable. Here’s a simple example of a bash scrip that captures user input and will then echo it back out:
echo "Type something and press Enter:"
read -e TEXT
echo $TEXT
When you run this script, “Type something and press Enter” will be outputted to the screen, and the cursor will allow you to type some text. After typing your text, press enter, and the script will echo the text you just typed back out.

Using the read -e VARIABLENAME command will place the user input from the keyboard into the variable called VARIABLENAME. The variable can then be used just like in the FTP example with the $ sign.
Cory Bohon is a freelance technology writer, indie Mac and iOS developer, and amateur photographer. Follow this article's author, Cory Bohon on Twitter.