Bash is a powerful scripting language that runs on Unix-like systems, including Linux and macOS. It's a versatile tool for automating tasks, managing files, and interacting with the system.
Basics
Shell Script: A text file containing a sequence of Bash commands.
Shebang: The first line of a script, indicating the interpreter to use (e.g., #!/bin/bash).
Execution: Make the script executable (chmod +x script.sh) and run it (./script.sh).
Essential Commands
echo: Prints text to the terminal.
read: Reads input from the user.
if-else: Conditional statements.
for: Loops through a list of items.
while: Loops as long as a condition is true.
case: Matches a value against patterns.
functions: Reusable blocks of code.
Variables
Declaration: variable_name=value
Usage: echo $variable_name
Types: String, integer, floating-point.
File Operations
Creating: touch filename
Deleting: rm filename
Copying: cp sourcefile destfile
Moving: mv sourcefile destfile
Listing: ls
Directing: cd directory
Input/Output
Reading: read variable
Writing: echo "text" > filename
Appending: echo "text" >> filename
Arithmetic Operations
Basic: expr 2 + 3
Shell Arithmetic: (( result = 2 + 3 ))
Control Flow
if-else:
Bash
if [ condition ]; then
commands
elif [ condition ]; then
commands
else
commands
fi
for loop:
Bash
for variable in list; do
commands
done
while loop:
Bash
while [ condition ]; do
commands
done
case:
Bash
case variable in
pattern1)
commands ;;
pattern2)
commands ;;
*)
commands ;;
esac
Functions
Defining:
Bash
function function_name() {
commands
}
Calling: function_name
Examples
Hello, World:
Bash
#!/bin/bash
echo "Hello, World!"
Simple calculator:
Bash
!/bin/bash
echo "Enter two numbers:"
read num1 num2
result=$((num1 + num2))
echo "The sum is: $result"
Regular Expressions
Pattern Matching: Used for complex string manipulation and searching.
Syntax: grep 'pattern' file
Example: Find lines containing email addresses: grep '[[:alnum:]]+@[[:alnum:]]+.[[:alnum:]]+' file
Pipes and Redirection
Pipes: Connect the output of one command to the input of another.
Example: List files, sort them by size, and print the top 10: ls -l | sort -n -k 5 | head -n 10
Redirection:
">": Overwrite output.
">>": Append output.
"<": Redirect input.
Command Substitution
Executing Commands Within Expressions: $(command) or command
Example: Set a variable to the current date: current_date=$(date)
Arrays
Declaration: array_name=(element1 element2)
Accessing: echo ${array_name[index]}
Example: Create an array of fruits: fruits=("apple" "banana" "orange")
Functions with Arguments
Passing Arguments: function_name arg1 arg2
Accessing Arguments: $1, $2, ...
Example:
Bash
function greet() {
echo "Hello, $1!"
}
greet John
Conditional Expressions
Test Brackets: [ condition ] or [[ condition ]]
Operators: -f (file), -d (directory), -x (executable), -z (empty), -n (non-empty), =, !=, <, >, -eq, -ne, -lt, -le, -gt, -ge
Example: Check if a file exists: if [ -f file.txt ]; then ...
Debugging
Tracing: set -x
Error Checking: if [ $? -ne 0 ]; then ...
Logging: echo "Message" >> logfile
Best Practices
Clarity and Readability: Use meaningful variable names and comments.
Error Handling: Anticipate potential errors and provide informative messages.
Modularity: Break down complex scripts into smaller functions.
Efficiency: Optimize your scripts for performance.
Advanced Topics
Here Documents: Multi-line input within a script.
Getopts: Parsing command-line options.
Signal Handling: Responding to interrupts and signals.
Background Jobs: Running commands in the background.
Shell Options: Customize Bash behavior (e.g., set -e for strict error checking).
Top comments (4)
Great article! Loving seeing quality content about bash scripting like this. Keep it up!
Nice.
My
man bash
saysEvaluation is done in fixed-width integers
. You have to use special tools likebc
to get floating point to do anything.Bash scripting: where a missing semicolon can make you question all of your life choices. :-)
It's not that bad. If you put things on separate lines, you don't need any semicolons except in one form of the
for
statement.By comparison, I once typed in a 20 line FORTRAN IV program (I'm old) and spent a whole night debugging it because I had mistyped one comma as a period where both were legal.
Something like
y = funct(1.2)
that should have beeny = funct(1, 2)
that passed one argument to the function instead of two. But that's how you learn good style and defensive programming! :)