Welcome to Episode 3
This episode is mostly about variables, which are names for places in memory where you will store values. Values can be strings of characters or numbers. Bash doesn’t require you to choose which type of value you are going to use to fill your variable.
Variables in Bash Scripting
The script below shows how to assign and use a simple variable. In general, shell variables are all treated as strings. A string is a series of characters, the content of which are ignored by the shell. Shell programming required you to get the syntax right. In the assignment there must be no space between the variable name and the equals sign, or the equals sign and the value. To use the variable, it is prefixed by a dollar ‘$‘ character.
#!/bin/sh # name is a variable name="Ferdinand" # This is an assignment of a value to a variable # called “name.” echo "The name is $name" # This line is calling the variable # called name.
The script above would generate a line that read, “The name is Ferdinand”
The special variables $1-$9 correspond to the arguments passed to the script when it is invoked. For example, if we rewrite the script above as shown below, calling the script Yourname.sh, and then invoke the command Yourname.sh Ferdinand Quacker, the message “Your name is Ferdinand Quacker” will be printed out:
#!/bin/sh # Yourname.sh echo "Your name is $1 $2" wolf@Lab5-ubustudio:~$ sudo chmod +x Yourname.sh [sudo] password for wolf: wolf@Lab5-ubustudio:~$ ./Yourname.sh Your name is wolf@Lab5-ubustudio:~$ ./Yourname.sh Ferdinand Quacker Your name is Ferdinand Quacker
Where I “forgot” to define the variables $1 and $2, the script ran great but produced no visible output.
Naming Conventions in Bash Scripting
You can choose almost any name for your variables, and textbooks often use one-letter variable names such as “A,” “B” and “C.” This makes a short example for the textbook, and in certain situations is the best kind of name for a variable. Some requirements of bash variable names are that they cannot contain spaces and they cannot start with a digit. Many sources for bash scripting help suggest you always use upper-case letters in a variable name, like “WEIGHT,” or that you always use lower-case letters, like “weight.” It is most important to keep some regularity in your variable-naming.
The most common conventions are
Single word: Where the name of the variable is a single word that is descriptive of what the content of the variable will be. “height,” “weight,” “colour,” “description” or understandable shortenings of the words like “desc,” “mnths,” “hght,” and so on. Keep in mind that the name of a variable can help future readers of your code to understand what you meant the script to do. That future reader might be you!
Underscore_Separated words: Where the variable name is two or more words separated by an underscore. Underscore is the name for the character that results from holding the shift key down and tapping the hyphen or dash. “_” between words is treated by the shell program as if there is no space between the words but is readable as if there is a space, e.g., “points_scored,” “monthly_expenses,” “sum_of_entries” This convention makes the code easier to read.
CamelCase or StudlyCapitals: CamelCase uses two or more words to name a variable, but instead of an underscore, camelCasing capitalizes the first letter of the internal words.
Arithmetic in Bash Scripting
Shell scripts can also do math but it is not a great way to spend your (computer’s) time. The script below will produce a Fibonacci sequence. A Fibonacci sequence takes one number and adds the next number to it to produce the third in the sequence and then takes #’s 2 and 3 to make #4 in the sequence and so on. In a Fibonacci sequence, denoted by F0 , F1 , F2 , F3 , F4 , … [where the subscribed numbers ( 0, 1, 2, 3, 4 , … ) are indices identifying the consecutive members of the sequence], any member is the sum of its two immediate predecessors. Thus, beginning with F0 = 0 and F1 = 1 , for j = 2, 3, 4 , 5, … , every Fj = Fj-1 + Fj-2 .” If you set the MAX constant to 40, you will notice that it takes more than twice as much time as calculating 20 entries in the Fibonacci series. Simple formulae work quickly enough, but long and complicated formulae may work better in in compiled programs. There are ways to have Bash scripts call compiled program modules, so there is no problem if you really must have a complicated problem to solve.
#!/bin/bash # fibonacci.sh : Fibonacci sequence MAX=20 # a constant, denoting Number of terms (+1) to generate. MIN=2 # another constant. #If index is less than 2, then Fibo(index) = index. Fibonacci () { fsn=$1 if [ "$fsn" -lt "$MIN" ] then echo "$fsn" # First two terms are 0 1 ... see above. else (( --fsn )) # j-1 term1=$( Fibonacci $fsn ) # Fibo(j-1) (( --fsn )) # j-2 term2=$( Fibonacci $fsn ) # Fibo(j-2) echo $(( term1 + term2 )) fi } for i in $(seq 0 $MAX) do # Calculate $MAX+1 terms. FIBO=$(Fibonacci $i) echo -n "$FIBO " done # expected output: # 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 echo " " exit 0
If you copy the script into a file and run it, the first few numbers are found quite rapidly, but you could produce the last 10 places in the sequence on paper or (possibly) in your head without a calculator before the shell script could find them.
Shell Variables
Like every other programming language, shells support variables. Shell variables may be assigned values, manipulated, and used. Some variables are automatically assigned for use by the shell. Some variables are environmental variables. These variables can effect how programs run outside of the shell, and you might want to be careful naming your shell variables the same as any of these. The following is a list of the environmental variables on Lab5-ubustudio. Note: I am calling the env list from a different directory, and it is all in my command prompt. Your machine might only show you only the last directory in the path. You can customize this by changing the Environmental Variable that holds the prompt information. That Variable is PS1 at the top of the abbreviated list below. You may notice that the Environmental Variables below are all centered around a specific user If somebody else were to log in to this machine, a lot of the Environmental Variables would be changed. Another way to look at how your system is set up is to type set at the command line. That will show you even more Environmental Variables.
wolf@Lab5-ubustudio:~/Documents/Projects/basho$ env
PS1=’\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\u@\h:\w\$ ‘
ORBIT_SOCKETDIR=/tmp/orbit-wolf
TERM=xterm
SHELL=/bin/bash
USER=wolf
USERNAME=wolf
XDG_CONFIG_DIRS=/usr/share/ubuntustudio-menu/:/etc/xdg/
DESKTOP_SESSION=gnome
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
PWD=/home/wolf/Documents/Projects/basho
GDM_KEYBOARD_LAYOUT=us
LANG=en_US.UTF-8
GDM_LANG=en_US.UTF-8
GDMSESSION=gnome
SHLVL=1
HOME=/home/wolf
LOGNAME=wolf
COLORTERM=gnome-terminal
This is the end of episode 3. Please stay tuned for another riveting episode soon.
== Wolf Halton is CEO of Atlanta Cloud Technology, Inc. , a guest writer on security topics here, at and owner of Wolfhalton.info.