Commands are written line by line. Use semicolon ;
to separate multiple commands on one line.
echo "First"; echo "Second"
Commands are written line by line. Use semicolon ;
to separate multiple commands on one line.
echo "First"; echo "Second"
# Setting a variable
name="Alice"
echo "Name is: $name"
# Reading input into a variable
echo "Enter your favorite color:"
read favorite_color
echo "Your favorite color is: $favorite_color"
# Exporting a variable to make it available to child processes
export PATH="$PATH:/usr/local/myapp/bin"
echo "Updated PATH: $PATH"
echo 'Single quotes: $HOME'
echo "Double quotes: $HOME"
echo `date`
# Preferred modern syntax: $(command)
today=$(date '+%A, %B %d, %Y')
echo "Today is: $today"
current_user=$(whoami)
echo "Current user: $current_user"
echo "This is a quote: \""
echo -e "Line1
Line2"
ls # List directory contents
cd /path # Change to directory
pwd # Print working directory
cp source.txt destination.txt # Copy a file
mv oldname.txt newname.txt # Rename/move file
rm file.txt # Delete a file
rm -r folder/ # Delete directory recursively
mkdir new_folder # Create directory
rmdir empty_folder # Remove empty directory
touch newfile.txt # Create empty file or update timestamp
stat file.txt # File details
find . -name "*.sh" # Find files recursively
locate filename # Search file paths (needs updatedb)
cat file.txt # View entire file
less file.txt # Scrollable viewer (q to quit)
more file.txt # View page by page
head file.txt # First 10 lines
tail file.txt # Last 10 lines
tail -f log.txt # Live updates as file changes
cut -d":" -f1 /etc/passwd # Cut first field using colon delimiter
awk '{ print $1 }' file.txt # Print first column
sed 's/foo/bar/g' file.txt # Replace 'foo' with 'bar'
grep "search" file.txt # Search lines containing 'search'
sort file.txt # Sort lines alphabetically
uniq sorted.txt # Remove duplicate lines
wc -l file.txt # Line count
tee output.txt # Redirect output to file and screen
tr 'a-z' 'A-Z' # Convert lowercase to uppercase
chmod +x script.sh # Make script executable
chmod 644 file.txt # rw-r--r-- permissions
chown user file.txt # Change file owner
chgrp group file.txt # Change file group
umask # Show default permission mask
umask 022 # Set default mask to allow rw-r--r--
Each file has permissions for owner
, group
, and others
.
r - read
w - write
x - execute
Example: -rwxr-xr--
Owner: rwx (7), Group: r-x (5), Others: r-- (4)
ps aux # List all processes
top # Real-time system monitor
htop # Enhanced top (install separately)
kill 1234 # Kill process by PID
killall firefox # Kill all processes by name
pkill -f "pattern" # Kill using pattern match
./script.sh & # Run in background
nohup ./script.sh & # Run in background, immune to hangups
disown # Remove job from shell's job table
jobs # List current jobs
fg %1 # Bring job 1 to foreground
bg %1 # Resume job 1 in background
command > file.txt # Redirect stdout (overwrite)
command >> file.txt # Redirect stdout (append)
command < input.txt # Take input from file
command 2> error.log # Redirect stderr
command > all.log 2>&1 # Redirect stdout and stderr to same file
cat file.txt | grep "search" # Output of one command becomes input of another
cat list.txt | xargs rm # Run rm for each line in list.txt
find . -name "*.log" | xargs rm
x=5
# if
if [ "$x" -lt 10 ]; then
echo "x is less than 10"
fi
# if-else
if [ "$x" -eq 10 ]; then
echo "x is 10"
else
echo "x is not 10"
fi
# if-elif-else
if [ "$x" -gt 10 ]; then
echo "x is greater than 10"
elif [ "$x" -eq 10 ]; then
echo "x is 10"
else
echo "x is less than 10"
fi
case $fruit in
apple)
echo "Apple pie!";;
banana)
echo "Banana smoothie!";;
*)
echo "Unknown fruit";;
esac
for i in 1 2 3; do
echo $i
done
while [ $x -lt 5 ]; do
echo $x
x=$((x+1))
done
until [ $x -eq 5 ]; do
echo $x
x=$((x+1))
done
for i in {1..10}; do
if [ $i -eq 3 ]; then
continue
fi
if [ $i -eq 7 ]; then
break
fi
echo $i
done
select option in "Start" "Stop" "Exit"; do
echo "You chose: $option"
break
done
greet() {
echo "Hello, $1!"
}
greet "Alice"
Functions in Bash can accept arguments, which are accessed using special variables like $1
, $@
, and $#
.
my_func() {
echo "First: $1"
echo "Second: $2"
echo "All: $@"
echo "Count: $#"
}
my_func "apple" "banana" "cherry"
Bash functions can return integer values (0–255) using the return
statement. These are typically used to indicate success (0) or failure (non-zero), and can be accessed using $?
immediately after the function call.
is_even() {
return $(( $1 % 2 ))
}
is_even 4
if [ $? -eq 0 ]; then
echo "Even"
else
echo "Odd"
fi
Conditional expressions using [ ]
and [[ ]]
. [[ ]]
is more flexible for string operations and supports pattern matching.
a=5
b=10
str="hello"
[ "$a" -eq "$b" ] # False: a is not equal to b
[ "$a" -ne "$b" ] # True: a is not equal to b
[[ "$str" == "hello" ]] # True: string comparison
[[ "$str" == h* ]] # True: pattern match with [[ ]]
[ "$a" = "$b" ] # Equal
[ "$a" != "$b" ] # Not equal
[ -z "$a" ] # Empty string
[ -n "$a" ] # Non-empty string
Bash supports basic regular expressions within double square brackets using the =~
operator. This allows pattern matching against strings.
word="hello123"
# Check if the word contains only letters
[[ $word =~ ^[a-zA-Z]+$ ]] && echo "Only letters"
# Check if the word contains only digits
[[ $word =~ ^[0-9]+$ ]] && echo "Only digits"
# Check if the word starts with "hello"
[[ $word =~ ^hello ]] && echo "Starts with 'hello'"
Globbing allows pattern-based matching of filenames and paths. It is commonly used to match multiple files using wildcards like *
, ?
, and character sets []
.
*.txt # Matches all files ending in .txt
file?.txt # Matches file1.txt, fileA.txt (any single character)
file[1-3].txt # Matches file1.txt, file2.txt, file3.txt
arr=(one two three)
echo ${arr[0]}
for i in "${arr[@]}"; do
echo $i
done
echo "Length: ${#arr[@]}"
declare -A colors
colors[apple]=red
colors[banana]=yellow
echo ${colors[apple]}
The shebang line at the top of a script specifies the path to the interpreter that should execute the script. It must be the very first line in the file.
#!/bin/bash
echo "Running with Bash"
echo "Script name: $0"
echo "First arg: $1"
echo "All args: $@"
echo "Arg count: $#"
command
if [ $? -eq 0 ]; then
echo "Success"
else
echo "Failure"
fi
exit 1 # Exit script with status 1
set -x # Echo commands before execution
set -e # Exit on error
# Debian/Ubuntu
sudo apt update && sudo apt install package
# Red Hat/CentOS
sudo yum install package
# Arch Linux
sudo pacman -S package
# macOS (Homebrew)
brew install package
uname -a # Kernel and system info
whoami # Current user
hostname # Hostname of system
df -h # Disk usage by mounted filesystems
du -sh * # Disk usage of current directory contents
free -h # Memory usage
uptime # System uptime and load average
env # Show all environment variables
printenv PATH # Show specific environment variable
ping example.com # Check connectivity
curl http://example.com # Get HTTP content
wget http://example.com # Download a file
ssh user@host # Remote login
scp file user@host:/path # Copy file to remote server
rsync -av src/ dest/ # Sync directories
netstat -tuln # Network ports (deprecated)
ss -tuln # Modern alternative to netstat
ifconfig # Show interfaces (deprecated)
ip addr # Show interfaces (replacement)
crontab -e # Edit user's cron jobs
crontab -l # List cron jobs
# Example: run every day at 6am
0 6 * * * /path/to/script.sh
alias ll='ls -la'
unalias ll
alias grep='grep --color=auto'
history # Show command history
!! # Run last command
!42 # Run command number 42
!git # Run last command starting with 'git'
trap "echo Goodbye!" EXIT # Run on script exit
trap "cleanup" INT # Run on Ctrl+C (SIGINT)
sleep 60 # Wait to allow trap test
Comments (#)
Anything after
#
is considered a comment and ignored by the shell.