You are on page 1of 3

Essentials for Scientific Computing:

Shell Scripting
Exercises
Ershaad Ahamed
TUE-CMS, JNCASR

May 2012

1. Below is our uniquefruits.sh script

#!/bin/bash

for filename in "$@"


do
sort "$filename" | uniq
done

The script reads each file specified as a command line argument, removes
duplicate lines and writes the result to stdout. If two or more files contain
lines with the same content, our script will not remove those duplicates.
Modify the program so that it removes duplicates globally (that is across
all files). For example, consider the following two files input1.txt and
input2.txt.

$ cat input1.txt
apple
mango
carrots
peas
pears
apple
strawberry
apple

and

$ cat input2.txt
mango
pineapple
strawberry
strawberry
watermelon
apple
apple

1
If we run our original script. We get the output.

$ ./uniquefruits.sh input1.txt input2.txt


apple
carrots
mango
pears
peas
strawberry
apple
mango
pineapple
strawberry
watermelon

Notice that there are duplicates in the output. The output that we expect
from our modified program is the following.

$ ./uniquefruits.sh input1.txt input2.txt


apple
carrots
mango
pears
peas
pineapple
strawberry
watermelon

Notice that there are no duplicates in the output.


Hint: You don’t need the for loop.
2. Below is isscript.sh that checks whether a file is a script or not

#!/bin/bash

if grep "/bin/bash" "$1"


then
echo "File is a shell script"
else
echo "File is not a shell script"
fi

There are two problems with this script. First, the script can be fooled
into detecting a file as a script if it contains the line /bin/bash anywhere
in the file. Shell scripts contain #!/bin/bash only on the first line. Thus
our script has to check only the first line. Fix this in the script.
In our script we actually need to search for #!/bin/bash and not /bin/bash.
Try running the follwing command at the prompt.

$ grep "#!/bin/bash" uniquefruits.sh

2
If grep found a match, it is supposed to print the matching line. But the
command above does not do what is expected and prints an error. How
can we search for #!/bin/bash on the command prompt. A hint can be
found by reading the quoting section of the bash man page. To see that
section, first open the manpage with

$ man bash

Then search for the QUOTING section by first pressing the / character
to begin a search and then typing QUOTING and then pressing ENTER.
3. The cwords.sh script is present on the class webpage. Modify the script
so that it counts the number of unique words in the text. Since you will
not be specifying any word to look for $1 will be unnecessary in this script.

You might also like