Bash (Bourne Again Shell) is a Unix shell and command language used for:
- Automating tasks
- Server administration
- DevOps pipelines
- System monitoring / log processing
Check your shell:
echo $SHELL
bash --versionRun a script:
bash script.sh
# OR make executable
chmod +x script.sh
./script.shShebang line (must be first line of every script):
#!/bin/bash#!/bin/bash
# My first bash script
echo "Hello, $(whoami)! Today is $(date)."chmod +x script.sh
./script.shname="Alice"
echo "Hello $name"read -p "Enter your name: " username
echo "Welcome, $username"today=$(date +%A)
echo "Today is $today"echo $HOME
echo $PATH
export API_KEY="12345"#!/bin/bash
num=10
if [ $num -gt 5 ]; then
echo "Greater than 5"
elif [ $num -eq 5 ]; then
echo "Equal to 5"
else
echo "Less than 5"
fi| Test | Meaning |
|---|---|
-e file |
Exists |
-f file |
Regular file |
-d dir |
Directory |
-r file |
Readable |
-w file |
Writable |
-x file |
Executable |
-s file |
Not empty |
if [ -f "/etc/passwd" ]; then
echo "File exists"
fiif [ "$a" = "$b" ]; then
echo "Equal"
fi
if [ -z "$str" ]; then
echo "Empty string"
fifor i in 1 2 3 4 5; do
echo "Number: $i"
doneWith range:
for i in {1..5}; do echo $i; doneWith command output:
for user in $(cat /etc/passwd | cut -d: -f1); do
echo "User: $user"
donecount=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
donex=1
until [ $x -gt 3 ]; do
echo "x is $x"
((x++))
doneread -p "Enter choice (start|stop): " choice
case $choice in
start)
echo "Starting service..."
;;
stop)
echo "Stopping service..."
;;
*)
echo "Invalid choice"
;;
esaca=5; b=3
expr $a + $ba=$((10 + 5))
b=$((a * 2))
echo $b((count++))
((count--))fruits=("apple" "banana" "cherry")
echo ${fruits[1]} # banana
echo ${fruits[@]} # all elements
echo ${#fruits[@]} # count
# Add element
fruits+=("mango")Loop through array:
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
donefunction greet() {
echo "Hello, $1!"
}
greet "Alice"Return value:
add() {
return $(( $1 + $2 ))
}
add 5 7
echo $? # shows 12#!/bin/bash
echo "Script name: $0"
echo "First arg: $1"
echo "Second arg: $2"
echo "All args: $@"
echo "Count: $#"Example:
./myscript.sh server1 server2| Symbol | Description |
|---|---|
> |
Redirect stdout (overwrite) |
>> |
Append |
< |
Input |
2> |
Redirect stderr |
&> |
Redirect both stdout + stderr |
ls > files.txt
ls /notfound 2> errors.logps aux | grep nginx
cat /etc/passwd | grep rootstr="HelloWorld"
echo ${str:0:5} # Helloecho ${str/World/Bash} # HelloBashecho ${#str}echo "Running command..."
if command; then
echo "Success"
else
echo "Failed"
fi
echo "Exit code: $?"
exit 0#!/bin/bash
read -p "Enter filename: " file
if [ -f "$file" ]; then
echo "File found!"
cat "$file"
else
echo "File not found!"
fibash -x script.shset -x # turn on debug
set +x # turn off debug
set -e # exit on errortrap "echo 'Script interrupted'; exit" SIGINT SIGTERMLOGFILE="/var/log/myscript.log"
echo "$(date) - Script started" >> $LOGFILEEdit crontab:
crontab -eExample entries:
0 * * * * /home/user/backup.sh
@daily /home/user/cleanup.sh
List:
crontab -lword="hello123"
if [[ $word =~ ^[a-z]+[0-9]+$ ]]; then
echo "Matched pattern"
fifiles=$(ls | wc -l)
echo "Total files: $files"RED='\033[0;31m'
NC='\033[0m'
echo -e "${RED}Error occurred${NC}"(command1 &) && (command2 &)
wait✅ Check service status
#!/bin/bash
service="nginx"
if systemctl is-active --quiet $service; then
echo "$service is running"
else
echo "$service is stopped"
fi✅ Ping Monitor
#!/bin/bash
for host in google.com 8.8.8.8; do
ping -c1 $host &> /dev/null && echo "$host UP" || echo "$host DOWN"
done✅ Log backup
#!/bin/bash
tar -czf /backup/logs_$(date +%F).tar.gz /var/log/*flowchart TD
A[Start Script] --> B[Read Variables]
B --> C{Condition?}
C -->|True| D[Execute Commands]
C -->|False| E[Print Message]
D --> F[Loop / Function]
F --> G[Log / Output]
G --> H[End Script]
Q: How do you handle errors in Bash? A: Use
set -eto stop on error or check$?. Combine withtrapfor clean exit.
Q: Difference between
>and>>? A:>overwrites file;>>appends.
Q: How to pass arguments to a script? A: Via
$1,$2,$@.
Q: How to check if a directory exists? A:
[ -d "/path" ] && echo "exists"
Q: What does
#!/bin/bashmean? A: It tells OS to use bash interpreter.
Q: How to debug bash scripts? A:
bash -x script.shor useset -xinside.
| Task | Command |
|---|---|
| Make script executable | chmod +x script.sh |
| Execute script | ./script.sh |
| Print variable | echo $var |
| Arithmetic | $((a+b)) |
| If condition | if [ cond ]; then ... fi |
| For loop | for i in {1..5}; do ...; done |
| Function | func() { ... } |
| Debug | bash -x script.sh |
| Redirect output | cmd > file |
| Append output | cmd >> file |
| Run in background | cmd & |