CIS120 Linux Fundamentals by Scott Shaper

Creating a Bash Script, Comments, Variables and Read

Bash scripts are like mini-programs that can save you hours of work. Think of them as a way to teach your computer to follow instructions - whether it's organizing files, processing data, or performing system maintenance. Once you write a script, you can run it anytime with a single command, and your computer faithfully executes all the steps you've defined.

Quick Reference: Essential Bash Scripting Elements

Element Description Common Use
#!/bin/bash Shebang line First line of every script to specify Bash interpreter
# Comment Comments Adding notes and explanations in your script
variable="value" Variable assignment Storing data for later use in the script
echo $variable Output text/variables Displaying information to the user
read variable User input Getting information from the user
chmod 700 script.sh Change permissions Making a script executable
./script.sh Run script Executing a script from its directory

Practical Example

In this example, we are creating a simple bash script. The script starts with the shebang line #!/bin/bash which tells the system to use bash to interpret the script. We then add a comment explaining what it is, and finally use echo to display a message. If use VIM you would start by typing vim simplescript.sh and then typing the script below into the file.

The line that starts with # is a comment. Comments are ignored by the interpreter and are used to explain the script. Comments are useful for documenting what the script does and how it works.

#!/bin/bash

#this is a comment it is ignored by the interpreter

echo "This is a simple script"

To run this script, you would first make it executable with chmod 700 simplescript.sh and then run it with ./simplescript.sh or bash simplescript.sh. The reason I want you to use chmod 700 is because it gives the owner read, write, and execute permissions. This is important because if the script is not executable, it will not run. Also other users will not be able to run or see the script.

Working with Variables

Variables in Bash scripts are containers that store data which can be used and manipulated throughout your script. They make scripts more flexible and reusable by allowing you to store values that might change, rather than hardcoding them into the script. A variable name can consist of letters, numbers, and underscores, but cannot start with a number and must never have a space in them. To assign a value to a variable, use the format variable_name=value (with no spaces around the equals sign), and to access a variable's value, prefix the variable name with a dollar sign $variable_name. NOTE: If you try to access a variable that has not been assigned a value, it will return an empty string.

Common Variable Operations

Operation What It Does When to Use It
name="value" Assigns a value to a variable When storing data for later use
echo $name Accesses the variable's value When using the stored data
${name} Explicitly defines variable boundaries When variable is used in a string and needs to be clearly defined
result=$(command) Captures command output When you need to use command results

Practical Examples

Basic variable assignment and usage

In this example, we are demonstrating basic variable assignment and usage. We assign a string value to var1, a numeric value to var2, and capture the output of a command into var3. We then echo each variable to display its value. Notice how we use ${var3} when concatenating to make sure the variable name is clearly defined.

#!/bin/bash

var1="this is a variable"

var2=5

var3=$(cat foo.txt)

echo $var1

echo $var2

echo $var3

echo "I am concatenating this to the contents of varible 3 (var 3) ${var3}"
Arithmetic operations with variables

In this example, we are demonstrating arithmetic operations with variables. We start with num1 set to 5. We then use ((num1++)) to increment num1 by 1. We can also use $((expression)) to perform arithmetic. When we write num1=$((num1+5)), we are assigning the result back to num1 (like x = x + y). When we write echo $((num1+5)), we are just calculating and displaying the result without changing num1 (like x + y).

#!/bin/bash

num1=5

((num1++)) #this increments by 1

echo $num1

num1=$((num1+5)) #this is like doing x = x + y

echo $num1

echo $((num1+5)) #this is like doing x + y

echo $num1
Advanced variable usage with heredoc

In this example, we are demonstrating more advanced variable usage using a heredoc (using <<TEST and TEST) which allows us to output multiple lines of text where quotes are treated literally but variables are still expanded. We can store the heredoc output in a variable using command substitution, then echo the variable to display it.

#!/bin/bash

variable=$(cat <<TEST
This is some "text"

where 'single' and "double" quotes are just printed

This is the contents of the foo.txt file ${d}


TEST
)

echo "$variable"

Getting User Input with 'read'

The read command is Bash's way of accepting input from the user during script execution. When the script encounters a read statement, it pauses and waits for the user to type something and press Enter. This input is then stored in a variable that you specify, allowing your script to use that information for later processing. The read command makes your scripts interactive, enabling them to respond differently based on user input rather than following a fixed path.

Common read Command Options

Option What It Does When to Use It
read variable Basic input collection When you need a single value from the user
read -p "Prompt: " variable Shows a prompt before input When indicating what input is needed
read -s variable Silent input (no display) When collecting sensitive information like passwords
read var1 var2 var3 Reads multiple values When collecting related pieces of information

Practical Examples

Basic read command

In this example, we are demonstrating the basic use of the read command. We first echo a question to the user, then use read to wait for their input. The input is stored in the variable name, which we then use in an echo statement to greet the user.

#!/bin/bash

echo "What is your name?"
read name
echo "Hello, $name!"
Reading multiple values

In this example, we are demonstrating how to read multiple values at once. When you use read first last, the read command will split the input by spaces and assign the first word to the first variable and the second word to the second variable. Any additional words will be assigned to the last variable.

#!/bin/bash

echo "Enter your first and last name:"
read first last
echo "Hello, $first $last!"
Using read with prompts and silent input

In this example, we are demonstrating the -p and -s options for the read command. The -p option allows you to include a prompt on the same line as the read command, which is useful for one-line requests. The -s option makes the input silent, meaning what the user types will not be displayed on the screen. This is useful for passwords and other sensitive information. Notice that we use -sp together to combine both options.

#!/bin/bash

#the -p is for prompt it will wait for a user response.  This is needed on one line requests.
read -p "Enter your username: " username 

#the -s is so whe the user types does not show.
read -sp "Enter your password: " password
echo "Username: $username, Password: [hidden]"

File System Navigation in Scripts

Bash scripts can navigate the file system and perform operations on files and directories just like you would manually. You can use commands like cd to change directories, ls to list files, mkdir to create directories, and rm to remove files and directories. Scripts can combine these commands to automate complex file system operations.

Practical Example

In this example, we are demonstrating file system navigation and operations in a bash script. The script navigates to the home directory, lists files, changes to a subdirectory, creates a new directory and file, lists the contents, and then removes the directory. This shows how scripts can automate a series of file system operations.

#!/bin/bash

echo
echo "*** START SCRIPT ***"
cd ~
echo "* List home directory"
ls -l
echo "* Go to playground/scripting directory"
cd playground/scripting/
echo "* Create scott directory and file.txt"
mkdir scott
echo "This is text" > scott/file.txt
echo "* List playground/scripting"
ls -l
echo "* List scott directory"
ls -l scott
echo "* Delete scott directory"
rm -r scott
echo "* Show that directory scott was deleted"
ls -l
echo "*** SCRIPT COMPLETE ***"
echo

Running and Managing Scripts

Common Script Execution Methods

Method What It Does When to Use It
chmod 700 script.sh Makes script executable Before running a script for the first time
./script.sh Runs script from current directory When the script is in your current location
bash script.sh Explicitly uses bash to run script When testing or the script isn't executable
/path/to/script.sh Runs script using full path When the script is in another location

Practical Example

In this example, we are demonstrating how to make a script executable and run it. First, we use chmod 700 to give the owner read, write, and execute permissions. Then we can run the script using ./script.sh if it's in the current directory, or bash script.sh to explicitly use bash to run it.

# Making a script executable
chmod 700 myscript.sh  # Owner can read, write, execute

# Different ways to run a script
./myscript.sh  # Run from current directory
bash myscript.sh  # Run with bash explicitly

Learning Aids

Tips for Success

Common Mistakes to Avoid

Best Practices