0% found this document useful (0 votes)
2 views12 pages

Shell Scripting Guide

This document is a comprehensive guide to shell scripting, covering essential topics such as commands, conditionals, loops, variables, functions, and input/output. It provides practical examples and explanations for beginners to understand how to automate tasks using Bash scripts. The guide also includes practice scripts and a quick reference card for easy access to key concepts.

Uploaded by

rishunaudiyal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views12 pages

Shell Scripting Guide

This document is a comprehensive guide to shell scripting, covering essential topics such as commands, conditionals, loops, variables, functions, and input/output. It provides practical examples and explanations for beginners to understand how to automate tasks using Bash scripts. The guide also includes practice scripts and a quick reference card for easy access to key concepts.

Uploaded by

rishunaudiyal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Shell Scripting

A Complete Beginner's Guide


Commands • Conditionals • Loops • Variables • Functions • I/O

1. Introduction to Shell Scripting


A shell is a command-line interpreter — it reads your instructions and tells the operating system
what to do. The most common shell on Linux and macOS is Bash (Bourne Again SHell).
A shell script is simply a text file containing a sequence of shell commands. Instead of typing
commands one by one, you write them in a file and run the whole file at once — that's
automation.

Your First Script


Create a file called [Link] and write the following:
#!/bin/bash
echo "Hello, World!"

The first line #!/bin/bash is called a shebang. It tells the OS which interpreter to use to run this
script. Always include it at the top.
To run it:
chmod +x [Link] # make it executable
./[Link] # run it
2. Essential Commands
Commands are the foundation of shell scripting. Every line you type is a command — an
instruction you give to the shell. The shell reads it, executes it, and shows you the result.

2.1 Navigation Commands


Command What it does Example
pwd Print current directory $ pwd → /home/rishabh
cd <path> Change directory cd ~/Desktop
ls List files in directory ls -la

How pwd works


The filesystem is like a tree of folders. At any moment, your shell is 'inside' one folder. pwd
prints the full path from the root / all the way to your current folder.
How cd works
cd moves you into a different folder. cd .. goes one level up. cd ~ teleports you home. cd
/absolute/path takes you to any exact location.
cd /home/rishabh # go to absolute path
cd .. # go up one folder
cd ~ # go to home directory

2.2 File Operations


Command What it does Example
mkdir <name> Create a new folder mkdir -p sem4/ada/notes
cp <src> <dst> Copy file or folder cp -r projects/ backup/
mv <src> <dst> Move or rename mv [Link] [Link]
rm <file> Delete file (permanent!) rm -i *.log
cat <file> Print file contents cat [Link]
touch <file> Create empty file touch [Link]

How rm works — CAUTION


rm permanently deletes files. There is no recycle bin in the shell. Use -i to confirm before each
deletion. Use -r to delete folders recursively.
2.3 Text Commands
Command What it does Example
echo <text> Print text to terminal echo "Hello $name"
grep <pat> Search for a pattern grep -i 'error' [Link]
<file>
wc <file> Count lines/words/chars wc -l [Link]
sort <file> Sort lines of a file sort [Link]
head / tail Show start or end of file tail -n 20 [Link]

How grep works


grep scans each line of a file and checks if it matches your pattern. -i makes it case-insensitive.
-r searches recursively inside all files in a folder. It's the go-to tool for searching logs and code.

2.4 System Commands


Command What it does Example
chmod <perm> Change file permissions chmod +x [Link]
<file>
ps aux List all running processes ps aux | grep python
kill <PID> Stop a process kill 1234
df -h Show disk space usage df -h
whoami Print current username whoami
date Show current date/time date +%F

How chmod works


Every file has three permission groups: owner, group, others. chmod +x adds execute
permission (makes a script runnable). Numeric mode 755 means owner can read/write/execute;
others can only read and execute.

3. Variables
Variables store data so your script can remember and reuse it. In Bash, variables are untyped
— they can hold text, numbers, or command output.
3.1 Declaring and Using Variables
Assign a value with =, access it with a $ prefix. There must be NO spaces around the = sign —
that is a strict Bash rule.
name="Rishabh"
age=20
echo "$name is $age years old"
echo "Hello, ${name}!" # use {} when next to other text

Why $ before the variable name?


Without $, Bash treats the name as literal text. With $, Bash substitutes the variable's current
value before running the command. This substitution is called parameter expansion.

3.2 Special Variables


Bash has built-in variables that hold useful information automatically — you don't assign them,
Bash does.
echo $0 # script name
echo $1 # first argument passed to script
echo $# # number of arguments
echo $@ # all arguments
echo $? # exit code of last command (0 = success)
echo $$ # PID of current shell

3.3 Command Substitution


Store the output of a command in a variable using $( ). Bash runs the command inside, captures
its output, and substitutes it.
today=$(date +%F)
user=$(whoami)
files=$(ls | wc -l)
echo "Today is $today, logged in as $user"
echo "Files in folder: $files"

3.4 Arithmetic with $(( ))


Inside $(( )), Bash switches to arithmetic mode. You can use +, -, *, /, % (modulo), ** (power)
directly without $ before variable names.
a=10
b=3
sum=$((a + b))
remainder=$((a % b))
power=$((2 ** 8))
echo "Sum=$sum Remainder=$remainder 2^8=$power"
Note: Bash only does integer arithmetic. 7/2 gives 3, not 3.5. Use 'bc' for decimals: echo
"scale=2; 7/2" | bc
4. Conditionals
Conditionals let your script make decisions. Instead of blindly executing every line, the script
checks a condition — is this true? — and takes different actions based on the answer.

4.1 if / else / fi
The shell evaluates the expression inside [ ]. If it returns true (exit code 0), the block after then
runs. If false, the else block runs. Every if must end with fi (if spelled backwards).
score=75

if [ $score -ge 60 ]; then


echo "Passed!"
else
echo "Failed."
fi

4.2 elif — chaining conditions


Bash checks each condition top to bottom. The moment one condition is true, it runs that block
and skips all remaining elif and else blocks.
marks=82

if [ $marks -ge 90 ]; then


echo "Grade: A"
elif [ $marks -ge 75 ]; then
echo "Grade: B"
elif [ $marks -ge 60 ]; then
echo "Grade: C"
else
echo "Grade: F"
fi

4.3 Comparison Operators


Operator Meaning Example
-eq Equal to [ $a -eq $b ]
-ne Not equal [ $a -ne $b ]
-gt Greater than [ $a -gt $b ]
-lt Less than [ $a -lt $b ]
-ge Greater or equal [ $a -ge $b ]
-le Less or equal [ $a -le $b ]
= String equal [ "$s" = "hi" ]
!= String not equal [ "$s" != "bye" ]
-z String is empty [ -z "$s" ]
-n String is not empty [ -n "$s" ]

4.4 File Condition Operators


Check properties of files before reading or writing them — to avoid errors if they don't exist.
if [ -f "[Link]" ]; then echo "File exists"; fi
if [ -d "projects/" ]; then echo "Directory exists"; fi

# -f = regular file exists


# -d = directory exists
# -e = file or directory exists
# -r = readable
# -w = writable
# -x = executable

4.5 case Statement


A cleaner way to handle many possible values of a variable, like a switch statement in other
languages. ;; acts like a break, * is the default wildcard.
day="Monday"

case $day in
"Monday") echo "Start of the week" ;;
"Friday") echo "Almost weekend!" ;;
"Saturday" | "Sunday") echo "Weekend!" ;;
*) echo "Midweek grind" ;;
esac

5. Loops
Loops let you repeat a block of code multiple times — over a list of items, a numeric range, or
as long as a condition is true. Loops are what make automation actually powerful.

5.1 for Loop


Bash takes the list you provide, assigns each item to the variable one at a time, runs the body
between do and done, then moves to the next item.
# Loop over a list
for fruit in apple banana mango; do
echo "I like $fruit"
done

# Loop over a number range


for i in {1..5}; do
echo "Count: $i"
done

# Loop over files


for file in *.txt; do
echo "Found: $file"
done

5.2 C-style for Loop


Just like C or Java. Three parts inside (( )): initialize; condition; increment. Before each iteration,
the condition is checked. If true, the body runs, then the increment happens.
for (( i=0; i<5; i++ )); do
echo "Iteration $i"
done

5.3 while Loop


Keeps repeating as long as a condition stays true. Before every iteration, the condition is
evaluated. Always make sure something inside the loop eventually makes the condition false —
otherwise you get an infinite loop.
count=1

while [ $count -le 5 ]; do


echo "Count is: $count"
count=$((count + 1)) # must increment!
done

5.4 until Loop


The opposite of while — runs as long as the condition is FALSE, stops when it becomes true.
Useful for 'keep trying until success' situations.
x=1

until [ $x -gt 5 ]; do
echo "x = $x"
x=$((x + 1))
done

5.5 break and continue


break immediately exits the loop. continue skips the rest of the current iteration and jumps to the
next one. Both work inside any loop type.
# break — stop at 5
for i in {1..10}; do
if [ $i -eq 5 ]; then break; fi
echo "$i"
done

# continue — skip even numbers


for i in {1..8}; do
if [ $((i % 2)) -eq 0 ]; then continue; fi
echo "Odd: $i"
done

6. Functions
Functions let you group commands under a name and reuse them. Define once, call as many
times as needed. This makes scripts cleaner and easier to maintain.

6.1 Defining and Calling


A function definition just stores the commands — it does not run them. Calling the function by
name is what executes it. Always define before calling.
greet() {
echo "Hello from the function!"
}

greet # call it

6.2 Functions with Parameters


Pass data using $1, $2, etc. inside the function. These are local to the function call and do not
overwrite script-level arguments.
greet() {
echo "Hello, $1! You are $2 years old."
}

greet "Rishabh" 20
# Output: Hello, Rishabh! You are 20 years old.

6.3 Returning Values


Bash's return only returns a numeric exit code. To return a real value, print it with echo inside
the function and capture it using $() when calling.
add() {
echo $(( $1 + $2 ))
}

result=$(add 10 5)
echo "Sum is: $result" # Sum is: 15
7. Input / Output
I/O is how your script talks to the world — reading from the user, writing to files, and chaining
commands together. Bash's redirection and pipe operators are extremely powerful.

7.1 read — User Input


The script pauses and waits for the user to type something. -p shows a prompt on the same
line. -s hides input (for passwords).
read -p "Enter your name: " name
echo "Welcome, $name!"

read -sp "Enter password: " pass


echo ""
echo "Password length: ${#pass}"

7.2 Output Redirection ( > and >> )


> creates or overwrites a file. >> appends to the end without deleting existing content. This is
how scripts write logs and save results.
echo "Build started" > [Link] # overwrites
echo "Step 1 done" >> [Link] # appends
ls -la >> [Link] # appends ls output

7.3 Pipes ( | )
Take the output of one command and feed it directly as input to the next. Bash runs both
simultaneously and connects them. You can chain as many pipes as you need.
ls -l | grep ".txt" # list only .txt files
cat [Link] | grep "error" # find errors in log
ps aux | grep python # find Python processes
ls | wc -l # count files
cat [Link] | sort | uniq # sort and deduplicate

8. Comments
Comments are lines the shell completely ignores. They are for humans reading the script, not
for the computer. Use them to explain what your code does.

8.1 Single-line Comments


Anything after # on a line is a comment. The only exception is the shebang #!/bin/bash on line 1
— that is NOT treated as a comment.
# This entire line is a comment
echo "Hello" # This is an inline comment
#!/bin/bash # This is the shebang (NOT a comment)

8.2 Multi-line Comments


Option 1 — Stack # on each line. This is the standard, recommended way:
# This is line one of the comment
# This is line two
# This is line three

Option 2 — The : '...' hack. The : command does nothing and ignores its argument. Use only to
temporarily disable large blocks of code:
: '
This is a
multiline comment block
using the colon trick
'
Tip: Stick with stacked # for all normal commenting. The : trick is only for temporarily
commenting out large chunks.

9. Practice Scripts
The best way to learn is to build scripts for things you actually do. Here are some beginner
exercises:

Sum of Numbers 1 to N
read -p "Enter N: " num
sum=0
i=1
while [ $i -le $num ]; do
sum=$((sum + i))
i=$((i + 1))
done
echo "Sum = $sum"

Factorial of N
read -p "Enter N: " num
fact=1
i=1
while [ $i -le $num ]; do
fact=$((fact * i))
i=$((i + 1))
done
echo "Factorial = $fact"
Prime Number Check
read -p "Enter a number: " num
i=2
is_prime=1
while [ $i -lt $num ]; do
if [ $((num % i)) -eq 0 ]; then
is_prime=0
break
fi
i=$((i + 1))
done
if [ $is_prime -eq 1 ]; then
echo "$num is prime"
else
echo "$num is not prime"
fi

10. Quick Reference Card

Shebang — always first line


#!/bin/bash

Run a script
chmod +x [Link]
./[Link]
bash [Link]

Variable rules
name="value" # no spaces around =
echo "$name" # $ to access value
echo "${name}x" # {} when adjacent to text

Arithmetic
result=$((10 + 3)) # use $(( ))
result=`expr 10 + 3` # old way — needs spaces

Always remember
• space after if and while keywords: if [ ... ] not if[
• close every if with fi, every while/for with done
• increment loop counter or risk infinite loop
• reset counter variable between separate loops
• use \* in expr for multiplication, * in $(( ))

You might also like