Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Bash / Shell Documentation

Drive your computer from the terminal — commands, pipes, permissions and automation scripts.

The shell is a text interface to your computer: you type commands, it runs programs. Bash is the most common shell on Linux, macOS (which now defaults to zsh — almost identical for everyday use) and servers. Knowing the terminal lets you navigate files, run tools like git/npm/docker, automate tasks with scripts and work on cloud servers over SSH.

1. Introduction & Setup

  • Linux / macOS: open the Terminal app.
  • Windows: install Git for Windows (gives Git Bash) or use WSL (wsl --install) for a full Ubuntu environment.
echo "Hello, Codify!"
whoami          # your user name
pwd             # print working directory
date +%Y        # current year

Output (first line):

Hello, Codify!

A script is a text file of commands:

#!/usr/bin/env bash
# hello.sh — the first line (shebang) says which interpreter runs the file
echo "Hello from a script"
chmod +x hello.sh     # make it executable
./hello.sh            # run it (or: bash hello.sh)

⚠️ Common error: Permission denied when running ./script.sh — add execute permission with chmod +x script.sh.

2. Basic Commands

pwd                      # where am I?
ls                       # list files
ls -la                   # long format, including hidden (.files)
cd projects              # go into a folder
cd ..                    # one level up
cd ~                     # home folder ( cd - goes back )
mkdir -p app/src         # create folders (with parents)
touch notes.txt          # create an empty file
cp notes.txt backup.txt  # copy   ( cp -r for folders )
mv backup.txt old.txt    # move / rename
rm old.txt               # delete ( rm -r folder ) — no recycle bin!
cat notes.txt            # print a file
less big.log             # scroll through a file (q to quit)
head -n 5 file; tail -n 20 file; tail -f app.log   # first/last lines, follow live
clear                    # clear the screen
man ls                   # manual page ( or: ls --help )

Shortcuts: Tab autocompletes, ↑ recalls previous commands, Ctrl+R searches history, Ctrl+C stops a running command, Ctrl+L clears.

mkdir -p demo/src
touch demo/README.md demo/src/app.js
cd demo
ls -R

Output:

.:
README.md
src

./src:
app.js

⚠️ Common error: rm -rf with a wrong or empty variable (rm -rf "$DIR/") can delete everything. Double-check paths and never run commands you don't understand.

3. Variables & Data Types

Bash variables are strings (no spaces around =). Use $name or ${name} to read them.

name="Asha"
age=20
course="Bash basics"
echo "Hi $name, you are $age"
echo "Course: ${course}!"
echo 'Single quotes keep $name literal'

today=$(date +%A)              # command substitution
files_count=$(echo a b c | wc -w)
echo "words: $files_count"

readonly PI=3.14
export APP_ENV="production"   # visible to child processes (environment variable)
echo "${#name} letters, upper: ${name^^}, first 2: ${name:0:2}"

fruits=("apple" "mango" "kiwi")   # indexed array
echo "${fruits[1]} ${#fruits[@]}"

Output:

Hi Asha, you are 20
Course: Bash basics!
Single quotes keep $name literal
words: 3
4 letters, upper: ASHA, first 2: As
mango 3

Special variables: $0 (script name), $1 $2 ... (arguments), $# (number of args), $@ (all args), $? (exit code of the last command), $$ (process id), $HOME, $PATH, $USER.

⚠️ Common error: name = "Asha" (spaces) runs a command called name. Write name="Asha".

4. Operators & Arithmetic

a=17
b=5
echo $((a + b)) $((a - b)) $((a * b)) $((a / b)) $((a % b)) $((2 ** 10))
((a++))
echo "a is now $a"

# comparisons inside [[ ]]
x=10
[[ $x -gt 5 ]] && echo "x > 5"
[[ "abc" == a* ]] && echo "starts with a"
[[ -z "" ]] && echo "empty string"

# decimals need bc or awk
echo "scale=2; 10/3" | bc 2>/dev/null || awk 'BEGIN { printf "%.2f\n", 10/3 }'

Output:

22 12 85 3 2 1024
a is now 18
x > 5
starts with a
empty string
3.33
Test Meaning
-eq -ne -lt -le -gt -ge integer comparison
== != < > string comparison (inside [[ ]])
-z str / -n str empty / non-empty string
-f file / -d dir / -e path file exists / directory exists / anything exists
-r -w -x readable / writable / executable
&& / `

⚠️ Common error: [ $x > 5 ] redirects output to a file named 5. Use -gt for numbers, or (( x > 5 )).

5. Conditional Statements

marks=78
if (( marks >= 90 )); then
  echo "Grade A"
elif (( marks >= 75 )); then
  echo "Grade B"
else
  echo "Grade C"
fi

file="config.txt"
if [[ -f "$file" ]]; then
  echo "$file exists"
else
  echo "$file not found"
fi

day="sat"
case "$day" in
  sat|sun) echo "weekend" ;;
  mon)     echo "back to work" ;;
  *)       echo "weekday" ;;
esac

mkdir -p logs && echo "logs ready"     # run the second only if the first succeeds

Output:

Grade B
config.txt not found
weekend
logs ready

⚠️ Common error: missing spaces inside brackets — [[$x -gt 5]] fails. Write [[ $x -gt 5 ]].

6. Loops

for i in 1 2 3; do echo -n "$i "; done; echo
for i in {1..5}; do echo -n "$i "; done; echo
for ((i = 10; i > 0; i -= 3)); do echo -n "$i "; done; echo

for lang in python java go; do
  echo "Learning $lang"
done

count=0
while (( count < 3 )); do
  ((count++))
done
echo "count=$count"

printf "a.txt\nb.txt\n" > list.txt
while IFS= read -r line; do         # read a file line by line
  echo "file: $line"
done < list.txt
rm list.txt

for n in {1..10}; do
  (( n % 2 == 0 )) && continue
  (( n > 7 )) && break
  echo -n "$n "
done
echo

Output:

1 2 3 
1 2 3 4 5 
10 7 4 1 
Learning python
Learning java
Learning go
count=3
file: a.txt
file: b.txt
1 3 5 7 

⚠️ Common error: for f in $(ls) breaks on file names with spaces. Use a glob: for f in *.txt; do ... done, and quote "$f".

7. Functions

greet() {
  local name="${1:-friend}"      # first argument, default "friend"
  echo "Hello, $name!"
}

add() {
  echo $(( $1 + $2 ))            # "return" a value by printing it
}

is_even() {
  (( $1 % 2 == 0 ))              # exit status: 0 = true, 1 = false
}

greet
greet "Ravi"
sum=$(add 4 9)
echo "sum=$sum"
if is_even 10; then echo "10 is even"; fi
is_even 7 || echo "7 is odd"

Output:

Hello, friend!
Hello, Ravi!
sum=13
10 is even
7 is odd

return n sets an exit status (0–255), not a value. Use local for variables inside functions so they don't leak.

⚠️ Common error: calling a function before it is defined in the script — define functions at the top.

8. Pipes, Redirection & Text Processing

The Unix idea: small tools that do one thing, combined with pipes |.

cat > marks.csv << 'EOF'
name,city,marks
Asha,Pune,91
Ravi,Delhi,78
Neha,Pune,85
Kabir,Delhi,66
EOF

tail -n +2 marks.csv | wc -l                         # number of students
grep "Pune" marks.csv                               # lines containing Pune
cut -d, -f1,3 marks.csv | tail -n +2 | sort -t, -k2 -nr | head -n 2   # top 2 by marks
awk -F, 'NR > 1 { sum += $3 } END { print "avg:", sum / (NR - 1) }' marks.csv
tail -n +2 marks.csv | cut -d, -f2 | sort | uniq -c | sort -nr | awk '{print $2": "$1}'
sed 's/Delhi/New Delhi/' marks.csv | grep -c "New Delhi"
rm marks.csv

Output:

4
Asha,Pune,91
Neha,Pune,85
Asha,91
Neha,85
avg: 80
Pune: 2
Delhi: 2
2
Syntax Meaning
cmd > file write output to a file (overwrite)
cmd >> file append
cmd < file read input from a file
cmd 2> err.log redirect errors
cmd > out.log 2>&1 output and errors to the same file
cmd > /dev/null discard output
`cmd1 cmd2`

Tools to know: grep (search), sed (replace), awk (columns/reports), cut, sort, uniq, wc, tr, xargs, find, tee.

⚠️ Common error: sort | uniq only removes adjacent duplicates — always sort before uniq.

9. Permissions & Processes

ls -l script.sh
# -rwxr-xr-- 1 asha dev 120 Oct 20 10:00 script.sh
#  │  │  └─ others: r--   (read only)
#  │  └──── group:  r-x   (read + execute)
#  └─────── owner:  rwx   (read + write + execute)

chmod +x script.sh        # add execute for everyone
chmod 755 deploy.sh       # rwx r-x r-x   (7 = 4 read + 2 write + 1 execute)
chmod 600 .env            # rw- --- ---   (private file)
chown asha:dev file.txt   # change owner (needs sudo)
sudo apt update           # run as administrator

Processes:

ps aux | grep node        # find running processes
top                       # live view ( htop is nicer )
kill 1234                 # stop process 1234 ( kill -9 forces )
node server.js &          # run in the background
jobs; fg %1               # list background jobs, bring one to the foreground
nohup node server.js > out.log 2>&1 &    # keep running after you log out
lsof -i :3000             # which process uses port 3000?
df -h; du -sh *           # disk space, folder sizes

⚠️ Common error: chmod 777 "fixes" permission errors by giving everyone full access — a security risk. Give only the permission that's needed.

10. Advanced Concepts

A robust script template:

#!/usr/bin/env bash
set -euo pipefail          # exit on error, on unset variables, and on pipe failures

usage() { echo "Usage: $0 <name> [count]"; exit 1; }
[[ $# -lt 1 ]] && usage

name="$1"
count="${2:-3}"

log() { echo "[$(date +%H:%M:%S)] $*"; }

for ((i = 1; i <= count; i++)); do
  log "Hello $name ($i/$count)"
done

Find and act on files:

find . -name "*.log" -mtime +7 -delete           # delete logs older than 7 days
find src -name "*.js" | xargs grep -n "TODO"     # search inside matching files
for f in *.jpeg; do mv "$f" "${f%.jpeg}.jpg"; done   # bulk rename extension
tar -czf backup-$(date +%F).tar.gz project/      # compress a folder

Remote work and automation:

ssh user@server.com                       # log in to a server
scp app.zip user@server.com:/var/www/     # copy a file to the server
curl -s https://api.github.com/users/octocat | grep '"name"'   # call an API
crontab -e                                # schedule: 0 2 * * * /home/asha/backup.sh
alias gs="git status"                     # shortcut (add to ~/.bashrc to keep it)

Here-strings, parameter expansion and traps:

file="report.final.pdf"
echo "${file%.*} | ${file##*.} | ${file/final/draft}"
upper=$(tr 'a-z' 'A-Z' <<< "codify")
echo "$upper"
trap 'echo "cleaning up"' EXIT
echo "script body"

Output:

report.final | pdf | report.draft.pdf
CODIFY
script body
cleaning up

Config files: ~/.bashrc (aliases, PATH for interactive shells), ~/.profile, and ~/.zshrc for zsh. Reload with source ~/.bashrc.

11. Examples with Output

Example 1 — Count words in a sentence and show the longest word (on a tie, the first one wins)

sentence="learning bash makes developers productive"
longest=""
for w in $sentence; do
  (( ${#w} > ${#longest} )) && longest="$w"
done
echo "words: $(wc -w <<< "$sentence"), longest: $longest"
words: 5, longest: developers

Example 2 — FizzBuzz

for i in {1..15}; do
  if (( i % 15 == 0 )); then echo -n "FizzBuzz "
  elif (( i % 3 == 0 )); then echo -n "Fizz "
  elif (( i % 5 == 0 )); then echo -n "Buzz "
  else echo -n "$i "
  fi
done
echo
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 

Example 3 — Simple backup with a timestamp

mkdir -p project backups
echo "data" > project/a.txt
stamp="2026-10-20"
tar -czf "backups/project-$stamp.tar.gz" project
ls backups
rm -rf project backups
project-2026-10-20.tar.gz

12. Practice Problems

  1. Create a folder structure myapp/{src,tests,docs} in one command and list it.
  2. Write a script that takes a file name and prints its number of lines, words and characters.
  3. Print all .txt files in a folder with their sizes, largest first.
  4. Write a script that checks whether a website is up (curl -s -o /dev/null -w "%{http_code}").
  5. From a CSV of students, print the average marks per city using awk.
  6. Write a backup script that keeps only the last 5 backups.
  7. Write a function mkcd that creates a folder and enters it; add it to ~/.bashrc.
  8. Find which process is using port 5000 and stop it.

13. Interview Questions

1. What is the difference between a shell and a terminal? The terminal is the window/program that shows text; the shell (bash, zsh) is the program that interprets the commands you type.

2. What does the shebang line do? #!/usr/bin/env bash tells the system which interpreter runs the script when you execute it directly.

3. > vs >>? > overwrites the file; >> appends to it.

4. What does $? contain? The exit status of the last command — 0 means success, non-zero means an error.

5. Single vs double quotes? Double quotes expand variables and command substitutions; single quotes keep everything literal.

6. What does set -euo pipefail do? Exit on any error (-e), treat unset variables as errors (-u), and fail a pipeline if any command in it fails (pipefail).

7. How do file permissions work? Read/write/execute bits for owner, group and others — numeric form rwx = 4+2+1, e.g. 755 or 644.

8. What is a pipe? cmd1 | cmd2 sends cmd1's standard output to cmd2's standard input, letting you chain small tools.

9. How do you run a process in the background and keep it after logout? Append &, and use nohup (or tmux/screen, or a service manager like systemd/PM2).

10. grep, sed and awk — when to use which? grep to find lines, sed to substitute/edit text streams, awk to work with columns and compute reports.

14. Cheat Sheet & References

Navigation and files

# move around
pwd; ls -la; cd dir; cd ..; cd ~; cd -
mkdir -p a/b; touch f.txt; cp -r src dst; mv old new; rm -rf dir
cat f; less f; head -n 10 f; tail -f log
find . -name "*.js"; du -sh *; df -h

Variables and strings

name="Asha"; echo "Hi $name"; echo "${name:0:2} ${#name} ${name^^}"
now=$(date +%F); export PATH="$HOME/bin:$PATH"
arr=(a b c); echo "${arr[0]} ${#arr[@]} ${arr[@]}"
file="a.tar.gz"; echo "${file%%.*} ${file##*.}"

Conditions and loops

if [[ -f file ]]; then echo yes; elif [[ -d dir ]]; then echo dir; else echo no; fi
(( n > 5 )) && echo big
case "$x" in a|b) echo ab ;; *) echo other ;; esac
for i in {1..5}; do echo $i; done
for f in *.txt; do echo "$f"; done
while read -r line; do echo "$line"; done < file

Functions and scripts

greet() { local n="${1:-you}"; echo "Hi $n"; }
set -euo pipefail
echo "$# args: $@"; exit 1
chmod +x script.sh && ./script.sh

Text processing

grep -rn "TODO" src; grep -i -c "error" log
sed -i 's/old/new/g' file
awk -F, '{ print $1, $3 }' data.csv
sort -nr | uniq -c | head
cut -d: -f1 /etc/passwd; tr 'a-z' 'A-Z'; wc -l file

Processes and system

ps aux | grep node; kill -9 PID; lsof -i :3000
cmd > out.log 2>&1 &; nohup cmd &; jobs; fg
chmod 755 f; chmod 600 .env; sudo chown user:group f
ssh user@host; scp f user@host:/path; curl -s URL

Official documentation