bash scripting: summary
Source: Dev.to
Bash Scripting Overview
A bash script is a plain‑text file that contains a sequence of commands executed by the Bash (Bourne‑Again SHell) interpreter, line by line.
Saving commands in a script lets you repeat the same steps many times simply by running the script file.
- Bash scripting is a powerful way to automate system tasks, manage resources, and perform routine operations on Unix/Linux systems.
- The terms bash and shell are often used interchangeably, though the shell is the command‑line interface that runs the Bash interpreter.
The Shell Prompt
shatakshi@truamateur$
- When a shell is waiting for a command it displays $ (regular user) or # (root).
- Common built‑in commands:
| Command | Description |
|---|---|
date | Show the current date and time |
pwd | Print the current working directory |
echo | Print a string or the value of a variable |
Script Naming & Shebang
- By convention Bash scripts end with
.sh, but the extension is not required. - Every Bash script should start with a shebang line, which tells the kernel which interpreter to use:
#!/bin/bash
The shebang is simply the absolute path to the Bash executable.
Example Script: run_all.sh
1. Create the file
# Open VS Code (or any editor) and create the file
code run_all.sh
2. Add the following content
#!/bin/bash
# Display the current date
echo "Today is $(date)"
# Ask the user for a directory path
echo -e "\nEnter the path to a directory:"
read the_path
# List the contents of the supplied path
echo -e "\nYour path contains the following files and folders:"
ls "$the_path"
3. Explanation of each line
| Line | Description |
|---|---|
#!/bin/bash | Shebang – points to the Bash interpreter |
echo "Today is $(date)" | Prints the current date ($(…) is preferred over back‑ticks) |
echo -e "\nEnter the path to a directory:" | Prompts the user (the -e enables interpretation of \n) |
read the_path | Reads the user input into variable the_path |
ls "$the_path" | Lists files/folders in the directory stored in the_path (quotes protect spaces) |
4. Make the script executable
chmod u+x run_all.sh # add execute permission for the file owner
5. Run the script
./run_all.sh
Note: You must be in the directory that contains
run_all.sh(or provide the full path).
Variables
- Bash variables store strings; there are no explicit data types.
- Variable names may start with a letter (
A‑Z,a‑z) or an underscore (_) and may contain letters, numbers, or underscores. - Variable names are case‑sensitive.
- Do not use reserved keywords (
if,elif,then, …) as variable names.
Setting & Using Variables
name=shatakshi # assignment (no spaces around =)
my_name=$name # use $ to expand the value
Example: Prompt for a name
#!/bin/bash
echo "What's your name?"
read entered_name
echo -e "\nHi $entered_name, hope you are having a good time learning Bash scripting."
Command‑Line Arguments
When a script is invoked, arguments are available as $1, $2, …
#!/bin/bash
echo "Hello, $1"
Running ./script.sh Alice prints Hello, Alice.
Input / Output Redirection
| Operation | Syntax | Description |
|---|---|---|
| Print to terminal | echo "hi" | Writes to standard output |
| Write to a file | echo "This is some text." > output.txt | Overwrites output.txt |
| Append to a file | echo "More text." >> output.txt | Adds to the end of output.txt |
Conditional Statements
#!/bin/bash
if [[ $a -gt 60 && $b -lt 100 ]]; then
echo "Both conditions are true"
elif [[ $a -gt 60 ]]; then
echo "Only a is greater than 60"
else
echo "Neither condition is true"
fi
[[ … ]]is the preferred test construct.- Logical operators:
&&(AND),||(OR). - The block is terminated with
fi.
Example: Positive / Negative / Zero
#!/bin/bash
echo "Please enter a number:"
read num
if [ "$num" -gt 0 ]; then
echo "$num is positive"
elif [ "$num" -lt 0 ]; then
echo "$num is negative"
else
echo "$num is zero"
fi
Loops
While Loop
#!/bin/bash
i=1
while [[ $i -le 10 ]]; do
echo "$i"
(( i += 1 )) # increment i
done
For Loop (Brace Expansion)
#!/bin/bash
for i in {1..5}; do
echo "$i"
done
The loop prints numbers 1 through 5.
Debugging
- Enable execution tracing with
set -xat the start of a script. Each command is printed prefixed by+.
#!/bin/bash
set -x # turn on debugging
# Your script commands go here
- Bash sets an exit status (
$?) after each command. A non‑zero value indicates an error and can be tested:
some_command
if [ $? -ne 0 ]; then
echo "some_command failed"
fi
Summary
- Bash scripts automate repetitive command‑line tasks.
- Begin every script with a shebang (
#!/bin/bash). - Use variables, user input, arguments, conditionals, and loops to build logic.
- Make scripts executable with
chmod u+x. - Debug with
set -xand check exit codes ($?).
With these fundamentals you can start writing your own Bash scripts to streamline everyday system administration and development workflows.
Bash Scripting Tutorial
Feedback is appreciated – thank you!
Twitter/X • Email
Understanding $?
$? holds the exit status of the last executed command.
- 0 – success
- Non‑zero – an error occurred
#!/bin/bash
# Your script goes here
if [ $? -ne 0 ]; then
echo "Error occurred."
fi
Example: Command that fails
#!/bin/bash
ls /some/folder/that/doesnt/exist
if [ $? -ne 0 ]; then
echo "Error occurred"
fi
Output
ls: cannot access '/some/folder/that/doesnt/exist': No such file or directory
Error occurred
Using read with a timeout
The read builtin almost always succeeds, but you can force a timeout to test the error path.
#!/bin/bash
echo "Enter a number (you have 3 seconds):"
read -t 3 num
if [ $? -ne 0 ]; then
echo "Error occurred"
fi
Output (when you don’t type anything for 3 seconds)
Enter a number (you have 3 seconds):
Error occurred
Debugging with echo
Printing variable values helps you see what’s being passed around.
#!/bin/bash
# Your script goes here
echo "Value of variable x is: $x"
# More code goes here
Exiting on any failure – set -e
If you want the script to stop immediately when any command fails, enable the errexit option.
#!/bin/bash
set -e # Exit on any command returning a non‑zero status
# Your script goes here
read -t 3 num # If this times out, the script exits here
echo "You entered: $num" # This line is never reached on timeout
Note: With
set -e, the script terminates as soon asread -t 3 numfails, so the subsequent$?check is never reached.
TL;DR
- Use
$?to inspect the exit status of the previous command. - Wrap checks in
if [ $? -ne 0 ]; then … fi. - Add
-ttoreadfor a timeout‑based error test. set -emakes the script abort on the first failure, simplifying error handling.
Thanks for reading! I hope this quick guide helps you understand Bash scripting a bit better.