A script contains echo $#; echo $1 $3; shift 2; echo $# $1; echo "$*" and is run as ./p.sh alpha beta gamma delta. What does it print?
Bourne shell (sh) scripts automate Linux administration. Learn the shebang, variables and quoting, positional and special parameters, read/echo/expr, test and [ ], if/case/for/while/until, functions, exit status, redirection and here-documents — with complete sample scripts and their output.
expr $a + $b, expr $a \* $b; capture the result with backquotes. POSIX shells also offer $(( )).The shell is both the command interpreter that reads what you type and a programming language. It expands variables and wildcards, sets up redirection, and runs programs. The original Bourne shell (sh) was written by Stephen Bourne at Bell Labs and shipped with Version 7 UNIX in 1979. Its descendants keep its syntax: the Korn shell ksh (David Korn, 1983), bash — the Bourne-Again SHell (Brian Fox for the GNU project, 1989) — and dash, the small POSIX shell that Debian and Ubuntu use as /bin/sh. The C shell csh/tcsh (Bill Joy) belongs to a different, C-like family. The POSIX standard defines the portable “sh” language that this topic follows.
#!/bin/sh
# hello.sh - my first Bourne shell script
echo "Hello, $USER"
echo "Today is `date +%A`"
echo "You are in `pwd`"#!/bin/sh — the shebang — tells the kernel which interpreter runs the file.chmod +x hello.sh (or chmod 755 hello.sh)../hello.sh (the ./ is needed because the current directory is normally not in PATH). sh hello.sh also works, and needs only read permission.. ./hello.sh runs the commands in the current shell, so variables it sets remain afterwards — that is how ~/.profile is read.#! followed by the interpreter's absolute path: #!/bin/sh for the Bourne/POSIX shell, #!/bin/bash for bash. Every other line beginning with # is a comment. A normal user's prompt is usually $, root's is #.Step through real scripts — watching variables, positional parameters and output change line by line — in the Bourne shell tracer tool on this page.
A variable is created by assignment, name=value, with no spaces around =. Names use letters, digits and underscores and cannot start with a digit. Every value is a string. $name or ${name} substitutes the value; the braces are needed when letters follow, as in ${name}s. With x=5, ${x}0 gives 50 but $x0 refers to a different, empty variable x0. unset name deletes a variable and readonly name freezes it.
| Quoting | Effect | With name=World | Output |
|---|---|---|---|
| Single quotes ' ' | Everything is literal — no expansion at all | echo 'Hello $name' | Hello $name |
| Double quotes " " | Spaces are kept, but $, backquote and \ stay special | echo "Hello $name" | Hello World |
| Backslash \ | Removes the special meaning of the next character | echo Price: \$5 | Price: $5 |
| Backquotes, or $( ) in POSIX shells | Command substitution: run the command and insert its output | echo "Now: $(date +%H:%M)" | Now: 10:15 |
name=World
echo 'Hello $name' # Hello $name
echo "Hello $name" # Hello World
echo Hello\ \ \ $name # Hello World (escaped spaces are kept)
echo "Files: `ls /etc/hosts`" # Files: /etc/hosts
echo "Price: \$5" # Price: $5
today=`date +%d-%m-%Y` # store a command's output in a variable
echo "Report for $today"The shell starts with environment variables already set: HOME (home directory), PATH (directories searched for commands), PS1 and PS2 (primary and secondary prompts), USER/LOGNAME, SHELL, PWD, IFS (field separators — space, tab, newline), TERM and MAIL. set lists all variables and env the exported ones. A variable is local to the current shell until it is exported; only exported variables are copied into the environment of child processes.
color=red
sh -c 'echo "child sees [$color]"' # child sees []
export color
sh -c 'echo "child sees [$color]"' # child sees [red]
PATH=$PATH:$HOME/bin ; export PATH # classic Bourne style: assign, then exportx = 5 is not an assignment — the shell runs a command named x with arguments = and 5 (“x: not found”). Write x=5. Likewise echo $x+1 prints 5+1: the shell does no arithmetic unless asked (expr or $(( ))).| Parameter | Meaning |
|---|---|
| $0 | Name of the script (as it was invoked) |
| $1 … $9 | The first nine command-line arguments; ${10} and beyond in POSIX shells (the original Bourne shell needed shift) |
| $# | Number of arguments (not counting $0) |
| $* | All arguments; quoted as "$*" they form one single word: "$1 $2 …" |
| $@ | All arguments; quoted as "$@" each stays a separate word: "$1" "$2" … — use this in loops |
| $? | Exit status of the most recent command (0 = success) |
| $$ | Process ID of the current shell — handy for unique temporary file names |
| $! | Process ID of the most recent background (&) command |
| $- | The options currently set in the shell |
#!/bin/sh
# args.sh - positional parameters and shift
echo "Script: $0"
echo "Count: $#"
echo "First: $1 Second: $2"
echo "All: $*"
shift
echo "After shift: \$1=$1, count=$#"
shift 2
echo "After shift 2: \$1=$1, count=$#"
# $ ./args.sh red green blue black
# Script: ./args.sh
# Count: 4
# First: red Second: green
# All: red green blue black
# After shift: $1=green, count=3
# After shift 2: $1=black, count=1shift n drops the first n arguments and decreases $# by n. set -- a b c replaces the positional parameters with a, b and c — useful for splitting a string into words. The difference between "$*" and "$@" matters when an argument contains spaces: called as ./s.sh "New Delhi" Kochi, a loop over "$*" runs once with [New Delhi Kochi], while a loop over "$@" runs twice, with [New Delhi] and then [Kochi].
read var reads one line from standard input into var. With several names, read a b c, the line is split into words using IFS: the first word goes to a, the second to b and all the remaining words to the last variable. Given the line one two three four, read a b sets a=one and b=“two three four”. echo prints its arguments followed by a newline; because echo's options and escapes (-n, \c, \t) differ between systems, printf is the portable choice for formatted output.
echo "Enter name and city:"
read name city
printf "Name: %s\nCity: %s\n" "$name" "$city"
# input: Anu Kochi
# output: Name: Anu
# City: KochiThe Bourne shell has no built-in arithmetic; the external command expr evaluates an expression and prints the result. Every operator and operand must be a separate argument, so spaces are compulsory, and characters special to the shell must be escaped: write \* for multiplication and \> \< for comparisons. expr works with integers only (division truncates). Its result goes to standard output, so it is captured with command substitution.
a=17
b=5
echo `expr $a + $b` # 22
echo `expr $a - $b` # 12
echo `expr $a \* $b` # 85 (an unescaped * would be expanded to file names)
echo `expr $a / $b` # 3 (integer division)
echo `expr $a % $b` # 2
expr $a \> $b # 1 (comparisons print 1 for true, 0 for false)
expr 2 + 3 \* 4 # 14 (* binds tighter than +)
x=`expr $a+$b` # no spaces: x is just the string 17+5
s=hello
expr "$s" : '.*' # 5 (length of the string)
echo $((a * b + 1)) # 86 POSIX arithmetic expansion
echo "scale=2; 10/3" | bc # 3.33 decimals need bci=$((i + 1)) does the same job without starting a new process. let is a bash/ksh extension, not Bourne shell.Conditions are commands: a command that exits with status 0 counts as true and any non-zero status as false. The test command — also spelt [ … ] — evaluates an expression and sets its exit status. Because [ is itself a command, spaces around the brackets and between all operands are compulsory: [ $x -gt 3 ], never [$x -gt 3].
| Kind | Operators | True when |
|---|---|---|
| Integer comparison | -eq -ne -gt -ge -lt -le | equal, not equal, greater than, greater or equal, less than, less or equal |
| String comparison | = != | the strings are identical / different |
| String tests | -z str -n str | the string has zero length / non-zero length |
| File tests | -e -f -d -r -w -x -s -L | exists; regular file; directory; readable; writable; executable; size > 0; symbolic link |
| Logical | ! -a -o | NOT, AND, OR inside one test (or join commands with && and ||) |
#!/bin/sh
# grade.sh - classify the marks given as $1
marks=$1
if [ $marks -ge 80 ]
then
echo "Distinction"
elif [ $marks -ge 60 ]
then
echo "First class"
elif [ $marks -ge 40 ]
then
echo "Pass"
else
echo "Fail"
fi
# ./grade.sh 85 → Distinction ./grade.sh 72 → First class
# ./grade.sh 40 → Pass ./grade.sh 12 → Failthen may share the line with the condition only after a semicolon: if [ -d "$dir" ]; then …. Quote variables inside tests — with an empty s, [ $s = abc ] becomes [ = abc ], a syntax error, while [ "$s" = abc ] works. Short forms: [ -f /etc/passwd ] && echo exists, cd /backup || exit 1.
[ 3 -eq 03 ] is true but [ "3" = "03" ] is false. Inside [ ], < and > are redirection operators, not comparisons — use -lt and -gt. And == is a bash extension; portable sh uses a single =.for word in yes Y no hello 42 file.txt
do
case $word in
[Yy]|[Yy]es) echo "$word: affirmative" ;;
[Nn]*) echo "$word: negative" ;;
[0-9]*) echo "$word: starts with a digit" ;;
*.txt) echo "$word: text file name" ;;
*) echo "$word: something else" ;;
esac
done
# yes: affirmative / Y: affirmative / no: negative /
# hello: something else / 42: starts with a digit / file.txt: text file namecase compares a word against wildcard patterns — * any string, ? any one character, […] one character from a set, and | separating alternatives. The first matching branch runs, up to its ;;, and esac (case backwards) closes the statement. A final *) branch acts as the default.
for f in apple banana cherry # for: once per word in the list
do
echo "fruit: $f"
done
i=1
while [ $i -le 3 ] # while: repeat as long as the test is TRUE
do
echo "while $i"
i=`expr $i + 1`
done
n=3
until [ $n -eq 0 ] # until: repeat as long as the test is FALSE
do
echo "until $n"
n=`expr $n - 1`
done
for i in 1 2 3 4 5 6
do
if [ $i -eq 2 ]; then continue; fi # skip the rest of this pass
if [ $i -eq 5 ]; then break; fi # leave the loop entirely
echo "loop $i"
done
# prints: fruit: apple, banana, cherry; while 1 2 3; until 3 2 1; loop 1 3 4break n and continue n act on the n-th enclosing loop. for f in *.txt loops over matching file names; for arg with no list loops over "$@". POSIX sh has no seq built in, so counting loops use while with expr. while read line; do …; done < file processes a file line by line, and while true or while : loops for ever (until break or exit).
#!/bin/sh
# func.sh - functions, return values and exit status
square() {
result=`expr $1 \* $1`
echo "$1 squared is $result"
}
is_even() {
if [ `expr $1 % 2` -eq 0 ]
then
return 0 # success = true
else
return 1 # failure = false
fi
}
square 7
for n in 4 7
do
if is_even $n
then
echo "$n is even"
else
echo "$n is odd"
fi
done
is_even 9
echo "status of is_even 9: $?"
echo "result is visible outside: $result"
# 7 squared is 49
# 4 is even
# 7 is odd
# status of is_even 9: 1
# result is visible outside: 49A function is defined as name() { commands; } (Bourne syntax has no function keyword) and must be defined before it is called. Inside it, $1, $2 … and $# refer to the function's own arguments. return n (0–255) ends the function and sets $?; exit n ends the whole script with that status. Variables are global by default — result above is still set after the call; local exists in bash and dash but is not part of POSIX.
| Operator | Meaning | Example |
|---|---|---|
| > file | Standard output to file (overwrite) | ls > list.txt |
| >> file | Standard output to file (append) | date >> log.txt |
| < file | Standard input from file | wc -l < log.txt |
| 2> file | Standard error (descriptor 2) to file | find / -name x 2> /dev/null |
| 2>&1 | Send standard error wherever standard output currently goes | cmd > all.txt 2>&1 |
| cmd1 | cmd2 | Pipe: cmd1's output becomes cmd2's input | who | wc -l |
| << WORD | Here-document: the following lines, up to WORD, become standard input | cat << EOF |
ls /etc/hosts /nonexistent > out1.txt 2>&1 # both streams go into out1.txt
ls /etc/hosts /nonexistent 2>&1 > out2.txt # only stdout in out2.txt; the error
# still appears on the terminal
echo first > log.txt # create or overwrite
echo second >> log.txt # append
wc -l < log.txt # 2
cut -d: -f7 /etc/passwd | sort | uniq -c # count users per login shell
cat << EOF
Dear $USER,
your backup finished at `date +%H:%M`.
EOF
cat << 'EOF'
Quoted delimiter, so no expansion: $HOME
EOF> file 2>&1 captures both streams, while 2>&1 > file sends errors to the old standard output (the terminal). /dev/null discards whatever is written to it.#!/bin/sh
# sumdigits.sh - sum of the digits of a number
echo "Enter a number:"
read n
sum=0
while [ $n -gt 0 ]
do
digit=`expr $n % 10`
sum=`expr $sum + $digit`
n=`expr $n / 10`
done
echo "Sum of digits = $sum"
# $ ./sumdigits.sh
# Enter a number:
# 4521
# Sum of digits = 12#!/bin/sh
# fact.sh - factorial of the number given as $1
if [ $# -ne 1 ]
then
echo "Usage: $0 number"
exit 1
fi
n=$1
fact=1
i=1
while [ $i -le $n ]
do
fact=`expr $fact \* $i`
i=`expr $i + 1`
done
echo "Factorial of $n is $fact"
# $ ./fact.sh 5
# Factorial of 5 is 120#!/bin/sh
# largest.sh - largest of three numbers
if [ $# -ne 3 ]
then
echo "Usage: $0 num1 num2 num3"
exit 1
fi
a=$1
b=$2
c=$3
if [ $a -ge $b ] && [ $a -ge $c ]
then
big=$a
elif [ $b -ge $c ]
then
big=$b
else
big=$c
fi
echo "Largest of $a, $b and $c is $big"
# $ ./largest.sh 12 45 7
# Largest of 12, 45 and 7 is 45#!/bin/sh
# ftype.sh - report the type of every name given on the command line
for f in "$@"
do
if [ ! -e "$f" ]
then
echo "$f: does not exist"
elif [ -d "$f" ]
then
echo "$f: directory"
elif [ -f "$f" ]
then
if [ -s "$f" ]
then
echo "$f: regular file, not empty"
else
echo "$f: regular file, empty"
fi
else
echo "$f: special file (device, pipe or socket)"
fi
done
# $ ./ftype.sh /etc notes.txt empty.txt /dev/null nosuch
# /etc: directory
# notes.txt: regular file, not empty
# empty.txt: regular file, empty
# /dev/null: special file (device, pipe or socket)
# nosuch: does not exist#!/bin/sh
# menu.sh - a menu driven by case
while true
do
echo "1) Date 2) Users logged in 3) Current directory 4) Quit"
echo "Enter your choice:"
read choice
case $choice in
1) date ;;
2) who ;;
3) pwd ;;
4) echo "Bye"
exit 0 ;;
*) echo "Invalid choice: $choice" ;;
esac
done
# choosing 3 prints the working directory, 9 prints "Invalid choice: 9",
# and 4 prints "Bye" and ends the script#!/bin/sh
# count.sh - count the lines and words of a file with a while-read loop
file=$1
if [ ! -f "$file" ]
then
echo "Usage: $0 file"
exit 1
fi
set -f # stop * and ? in the text from being expanded
lines=0
words=0
while read line
do
lines=`expr $lines + 1`
set -- $line # split the line: $# is now its number of words
words=`expr $words + $#`
done < "$file"
echo "Lines: $lines"
echo "Words: $words"
# $ ./count.sh notes.txt (3 lines: the quick brown fox / jumps over / the lazy dog)
# Lines: 3
# Words: 9
# The one-line equivalent: wc -l -w notes.txtTry the problem first, then reveal the working one step at a time.
A script contains echo $#; echo $1 $3; shift 2; echo $# $1; echo "$*" and is run as ./p.sh alpha beta gamma delta. What does it print?
With a=6 and b=4, predict the output of: (1) echo '$a + $b' (2) echo "$a + $b" (3) echo $a+$b (4) expr $a + $b (5) expr $a \* $b (6) expr $a / $b.
Trace sumdigits.sh (from this page) for the input 4521, showing digit, sum and n after each pass of the while loop.
/etc/hosts exists and /nonexistent does not. Compare ls /etc/hosts /nonexistent > out.txt 2>&1 with ls /etc/hosts /nonexistent 2>&1 > out.txt. What reaches the file and what reaches the screen? What is $? afterwards?
Write a Bourne shell script that reports whether the number given as its argument is prime, using a while loop and expr.
Predict the output of each command: (a) expr 7 / 2 (b) expr 7 % 3 (c) expr 3 \* 4 (d) expr 5 \> 3 (e) expr 2 + 3 \* 4 (f) expr 10 - 4 - 3.
Find and fix the errors: count = 0, then if [$count -lt 5], then count=$count+1, then echo Total: $count.
Write a script that prints the digits of the number given as its argument in reverse order (1234 → 4321).
Write a script that counts the regular files and the directories inside the directory given as its argument (the current directory if no argument is given).
10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.