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
- Start small - Begin with simple scripts that do one thing well, then build up complexity
- Test frequently - Run your script after adding each new feature to catch errors early
- Use meaningful variable names - Choose descriptive names that explain what the variable contains
- Add comments liberally - Your future self will thank you when revisiting old scripts
- Use consistent indentation - Proper spacing makes scripts much easier to read
- Create a scripts directory - Keep all your scripts organized in one place like ~/bin
- Learn from examples - Study other scripts to learn new techniques and best practices
- Use version control - Store your scripts in a Git repository for tracking changes
Common Mistakes to Avoid
- Forgetting spaces around operators - In Bash,
var=5assigns a value, butvar = 5tries to run a command called "var" - Misusing quotes - Double quotes allow variable expansion but single quotes don't
- Forgetting the shebang line - Without
#!/bin/bash, the system might use a different shell to run your script - Not making scripts executable - Forgetting
chmod 700means you'll get "permission denied" errors - Using spaces in variable names - Variables like
first namewon't work; usefirst_nameorfirstNameinstead - Forgetting the $ when using variables - Writing
echo nameprints "name", not the variable's value - Incorrect file paths - Using relative paths can break when running scripts from different locations
- Destructive commands without confirmation - Commands like
rmshould ask for confirmation in scripts
Best Practices
- Use functions for repeated code - Define functions for operations you perform multiple times
- Handle errors gracefully - Check for errors and provide helpful error messages
- Make scripts configurable - Use variables at the top of scripts for easy customization
- Document usage instructions - Include a comment section explaining how to use the script
- Check command success - Verify that commands succeed before proceeding with
if [ $? -eq 0 ] - Use consistent naming conventions - Adopt a standard naming pattern for all your scripts
- Include script headers - Add author, date, purpose, and usage information at the top
- Validate user input - Never trust user input without checking it first