Unix Shell Scripts¶
1. Write a bash shell script that prints “Hello, world” named
greet1.sh
. Make it executable and run from the command line like so
./greet1.sh
In [1]:
which bash
/bin/bash
In [2]:
cat > greet1.sh <<'EOF'
#!/bin/bash
echo "Hello, world"
EOF
In [3]:
chmod +x greet1.sh
In [4]:
./greet1.sh
Hello, world
2. Write greet2.sh
so that it outputs “Hello name” when run from
the command line, where name is a command line argument to
greet2.sh
. Note that name may consist of more than one word e.g.
greet2.sh Santa Claus
In [5]:
cat > greet2.sh <<'EOF'
#!/bin/bash
echo "Hello, $@"
EOF
In [6]:
chmod +x greet2.sh
In [7]:
./greet2.sh Santa Claus
Hello, Santa Claus
3. Write greet3.sh
so that it asks “What is your name?” when
executed, then prints “Hello name” when executed.
Note: This must be run from the terminal, as the notebook cannot accept interactive inputs.
In [8]:
cat > greet3.sh <<'EOF'
#!/bin/bash
echo -n "What is your name? "
read NAME
echo "Hello $NAME"
EOF
In [9]:
chmod +x greet3.sh
4. Write a function mean
to calculate the average of numbers
given to it as arguments to 4 significant places. For example
mean 1 2 3 4
should output 2.5000
.
In [10]:
function mean() {
sum=0
n=0
for x in $@
do
n=$((n+1))
sum=$(echo $sum + $x | bc)
done
echo "scale=4; $sum / $n" | bc -l
}
mean 1 2 3 4
2.5000
5. Save the function into a shell scirpt math.sh
, and use it in
a new bash session (open a second terminal) to find mean 1 2 3 4
as before.
In [11]:
cat > math.sh <<'EOF'
function mean() {
sum=0
n=0
for x in $@
do
n=$((n+1))
sum=$(echo $sum + $x | bc)
done
echo "scale=4; $sum / $n" | bc -l
}
EOF
In [12]:
source math.sh
mean 1 2 3 4
2.5000
In [ ]: