Monday 14 October 2013

Bash Exercise - 3

Script 11: Comparision
#!/bin/bash
a=4
b=5
# Here "a" and "b" can be treated either as integers or strings.
# There is some blurring between the arithmetic and string comparisons,
#+ since Bash variables are not strongly typed.
# Bash permits integer operations and comparisons on variables
#+ whose value consists of all-integer characters.
# Caution advised, however.
echo
if [ "$a" -ne "$b" ]
then
echo "$a is not equal to $b"
echo "(arithmetic comparison)"
fi
echo
if [ "$a" != "$b" ]
then
echo "$a is not equal to $b."
echo "(string comparison)"
# "4" != "5"
# ASCII 52 != ASCII 53
fi
# In this particular instance, both "-ne" and "!=" work.
echo
exit 0
Script 12: Continue
#!/bin/sh
rm -rf fred*
echo > fred1
echo > fred2
mkdir fred3
echo > fred4
for file in fred*
do
if [ -d "$file" ];then
echo "skipping directory $file"
# continue
fi
echo file is $file
done
#rm -rf fred*
exit 0
Script 13: Diff – if
#!/bin/bash
#Equivalence of test, /usr/bin/test, [ ], and /usr/bin/[
echo
if test -z "$1"
then
echo "No command-line arguments."
else
echo "First command-line argument is $1."
fi
echo
if /usr/bin/test -z "$1" # Same result as "test" builtin".
then
echo "No command-line arguments."
else
echo "First command-line argument is $1."
fi
echo
if [ -z "$1" ] # Functionally identical to above code blocks.
# if [ -z "$1" should work, but...
#+ Bash responds to a missing close-bracket with an error message.
then
echo "No command-line arguments."
else
echo "First command-line argument is $1."
fi
echo
if /usr/bin/[ -z "$1" ] # Again, functionally identical to above.
# if /usr/bin/[ -z "$1" # Works, but gives an error message.
# # Note:
# This has been fixed in Bash, version 3.x.
then
echo "No command-line arguments."
else
echo "First command-line argument is $1."
fi
echo
exit 0
Script 14: Disk
#!/bin/bash
tmpfile="/tmp/sh$$tmp"
for i in `awk -F: '{ if ($3 >= 500 ) print $6 }' /etc/passwd `
do
du -s $i >> $tmpfile
done
sort -rn $tmpfile
#rm $tmpfile
exit 0
Script 15: Execute
#!/bin/bash
for var in `ls`
do
`chmod u+x $var`
`chmod g+x $var`
`chmod o+x $var`
done

No comments :

Post a Comment