Bash Scripting
85
u
#! /bin/bash
v
# This is your second bash script. In this one,
you prompt
# the user for input, place the input in a variable, and
# display the variable contents in a string.
w
echo "What is your name?"
read name
x
echo "What chapter are you on in Linux Basics for Hackers?"
read chapter
y
echo "Welcome $name to Chapter $chapter of Linux Basics for Hackers!"
Listing 8-2: A simple script making use of variables
We
open with
#! /bin/bash
to tell the system we want to use the bash inter-
preter for this script u. We then add a comment that describes the script and
its functionality v. After that, we prompt the user for their name and ask
the interpreter to read the input and place
it into a variable we call
name
w.
Then we prompt the user to enter the chapter they are currently working
through in this book, and we again read the keyboard input into a variable,
this time called
chapter
x.
In
the final line, we construct a line of output that welcomes the reader
by their name to the chapter they are on y. We use the
echo
command and
provide the text we want to display on the screen in double quotes. Then, to
fill in the name and chapter number the user entered, we add the variables
where they should appear in the message. As noted in Chapter 7, to use the
values
contained in the variables, you must precede the variable name with
the
$
symbol.
Save this file as
WelcomeScript.sh. The
.sh extension is the convention for
script files. You might have noticed we didn’t include the extension earlier;
it’s
not strictly required, and it makes no difference if you leave the exten-
sion off. The extension can be a useful indicator for other people that this
file is a shell script, though.
Now, let’s run this script. Don’t forget to give yourself execute permis-
sion with
chmod
first; otherwise, the operating system will scold you with a
Permission denied
message.
kali >
./WelcomeScript.sh
What is your name?