bash Command
The Bourne Again Shell - a command-line interpreter and scripting language for Unix-like operating systems.
Syntax
bash [OPTIONS] [FILE [ARGUMENTS]]
bash [OPTIONS] -c STRING [ARGUMENTS]
bash [OPTIONS] -s [ARGUMENTS]
Bash is both an interactive command interpreter and a scripting language, serving as the default shell for most Linux distributions.
Common Options
| Option | Description |
|---|---|
-c STRING |
Execute commands from STRING |
-i |
Interactive shell |
-l |
Login shell |
-s |
Read commands from standard input |
-x |
Print commands before execution (debug mode) |
-e |
Exit immediately on error |
-u |
Treat unset variables as error |
-n |
Read commands but don't execute |
-v |
Print input lines as they are read |
--version |
Display version information |
Basic Usage
Interactive shell
# Start interactive bash shell
bash
# Start login shell
bash -l
# Start interactive shell explicitly
bash -i
# Exit shell
exit
Start and use bash interactively
Execute commands
# Execute single command
bash -c "ls -la"
bash -c "echo 'Hello World'"
# Execute multiple commands
bash -c "cd /tmp && ls -la && pwd"
# Execute with variables
bash -c 'echo "Current user: $USER"'
Execute commands directly from command line
Run scripts
# Run script file
bash script.sh
bash /path/to/script.sh
# Run script with arguments
bash script.sh arg1 arg2 arg3
# Run script from stdin
echo "echo 'Hello from stdin'" | bash -s
Execute bash scripts
Bash Scripting Basics
Script structure
#!/bin/bash
# This is a comment
# Variables
NAME="John"
AGE=30
# Output
echo "Hello, $NAME!"
echo "You are $AGE years old"
# Command substitution
CURRENT_DATE=$(date)
echo "Today is: $CURRENT_DATE"
Basic bash script structure
Control structures
#!/bin/bash
# If statement
if [ "$1" = "hello" ]; then
echo "Hello to you too!"
elif [ "$1" = "bye" ]; then
echo "Goodbye!"
else
echo "I don't understand: $1"
fi
# For loop
for i in {1..5}; do
echo "Number: $i"
done
# While loop
counter=1
while [ $counter -le 3 ]; do
echo "Counter: $counter"
((counter++))
done
Control flow in bash scripts
Functions
#!/bin/bash
# Function definition
greet() {
local name=$1
echo "Hello, $name!"
}
# Function with return value
add_numbers() {
local num1=$1
local num2=$2
echo $((num1 + num2))
}
# Call functions
greet "Alice"
result=$(add_numbers 5 3)
echo "5 + 3 = $result"
Define and use functions in bash
Debug and Error Handling
Debug mode
# Run script in debug mode
bash -x script.sh
# Enable debug mode in script
#!/bin/bash
set -x # Enable debug mode
echo "This will show the command"
set +x # Disable debug mode
# Verbose mode
bash -v script.sh
# Check syntax without execution
bash -n script.sh
Debug bash scripts
Error handling
#!/bin/bash
# Exit on error
set -e
# Exit on undefined variables
set -u
# Combine options
set -euo pipefail
# Error handling function
error_handler() {
echo "Error occurred in script at line: ${1}"
exit 1
}
# Trap errors
trap 'error_handler ${LINENO}' ERR
Handle errors in bash scripts
Advanced Features
Arrays
#!/bin/bash
# Indexed arrays
fruits=("apple" "banana" "orange")
echo "First fruit: ${fruits[0]}"
echo "All fruits: ${fruits[@]}"
echo "Number of fruits: ${#fruits[@]}"
# Add to array
fruits+=("grape")
# Loop through array
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done
# Associative arrays
declare -A colors
colors[red]="#FF0000"
colors[green]="#00FF00"
colors[blue]="#0000FF"
echo "Red color code: ${colors[red]}"
Work with arrays in bash
String manipulation
#!/bin/bash
text="Hello World"
# String length
echo "Length: ${#text}"
# Substring
echo "Substring: ${text:0:5}" # "Hello"
echo "From position: ${text:6}" # "World"
# Replace
echo "Replace: ${text/World/Universe}"
echo "Replace all: ${text//l/L}"
# Case conversion
echo "Uppercase: ${text^^}"
echo "Lowercase: ${text,,}"
# Remove prefix/suffix
filename="script.sh"
echo "Without extension: ${filename%.sh}"
String manipulation techniques
Environment and Configuration
Configuration files
# System-wide configuration
/etc/bash.bashrc
/etc/profile
# User-specific configuration
~/.bashrc # Non-login shells
~/.bash_profile # Login shells
~/.profile # General profile
~/.bash_logout # Logout actions
~/.bash_history # Command history
# Reload configuration
source ~/.bashrc
. ~/.bashrc
Bash configuration files
Environment variables
# View environment
env
printenv
# Set variables
export MY_VAR="value"
export PATH="$PATH:/new/path"
# Common variables
echo $HOME # Home directory
echo $USER # Current user
echo $PWD # Current directory
echo $SHELL # Current shell
echo $PATH # Executable paths
# Check if variable is set
if [ -n "$MY_VAR" ]; then
echo "MY_VAR is set to: $MY_VAR"
fi
Work with environment variables
Best Practices
Bash Scripting Best Practices
- Always use
#!/bin/bashshebang - Use
set -euo pipefailfor safer scripts - Quote variables to prevent word splitting
- Use
localfor function variables - Check command exit codes
- Use meaningful variable and function names
- Add comments to explain complex logic
- Validate input parameters
Common Pitfalls
- Unquoted variables - Can cause word splitting issues
- Missing error handling - Scripts continue after errors
- Hardcoded paths - Use relative paths or variables
- Not checking exit codes - Commands may fail silently
- Global variables in functions - Use local variables