Shell Script

One of the coolest part of UNIX command is that we can script series of commands for automating tasks.

Example

First, save following code into a file named “hello.sh”.

#!/bin/bash

echo "hello world"

Afterwards, change the permission (adding executable permission):

$chmod u+x hello.sh

Now, let’s execute the script:

$ ./hello.sh
hello world

If you modify the script as follows, output will also be changed:

#!/bin/bash

echo "hello world"
echo "good morning"
echo "good afternoon"
echo "good evening"

Let’s execute it again:

$ ./hello.sh
hello world
good morning
good afternoon
good evening

The cool thing is for printing 5 lines, we do not need to type the echo command 5 times.

Exercise

Let’s build a shell script which computes the total size of files in a folder specified by the first argument of the script.

Expected output:

$ ./filesize.sh DIRECTORY_NAME
Total size of files in the directory is 8 KB

Hint 1: Getting argument

#!/bin/bash

echo "argument 1" $1
echo "argument 2" $2

Hint 2: Getting the size of a file in KB:

$ du -s FILE_NAME

Hint 3: Using loop

#!/bin/bash

i=0
loop=3 # 3 times
while [ $i -lt $loop ]; do
  echo "loop" $i
  i=$(($i+1))
done

Compare number

-eq

==

-ne

!=

-lt

<

-gt

>

-le

<=

-ge

>=

Hint 4: Printing files in a directory

#!/bin/bash

files=`ls`
for f in ${files[@]}; do
  echo $f
done

Hint 5: Arithmetic computation

#!/bin/bash

one=1
two=2

ret=$(($one+$two))
echo "${one} + ${two} is ${ret}"

ret=$(($one*$two))
echo "${one} * ${two} is ${ret}"

Hint 6: Comparing string

#!/bin/bash

a1="hello world"
a2="hello world"
b="see you"

if [ "$a1" = "$a2" ]; then
  echo "a1 and a2 are same"
fi

if [ "$a1" != "$a2" ]; then
  echo "a1 and a2 are different"
else
  echo "a1 and a2 are same"
fi

if [ "$a1" != "$b" ]; then
  echo "a1 and b are different"
fi

Hint 7: showing N-th column

#!/bin/bash

cat /proc/cpuinfo
echo
echo "----- only showing 1st column -----"
echo
cat /proc/cpuinfo | awk '{ print $1 }'

Example Answer

#!/bin/bash

kb=`du -s $1/* | awk '{ print $1 }'`

total=0
for k in ${kb[@]}; do
      total=$(($total+$k))
done

echo "Total size of files in the directory is $total KB"