Unix Interview Prep Tutorial Part2- Simple unix scripts (Usage of IF, FOR Loops, While, Case, parameters, and importing variables from a file)
1) For usage for IF command in unix script, see the below sample script
#!/usr/bin/ksh
$num=3
if [ "$num" -gt "0" ];
then
echo "$num greater than 0"
else
echo "$num less than 0"
fi
2) For usage of FOR loop to read filenames from a filelist and move those files to a target directory, see the below example: (You can edit the $SOURCEDIR and $inputfilelist to the path you need for your purpose)
#!/usr/bin/ksh
$SOURCEDIR=/home/directorypath
starttime=`date +'%Y-%m-%d %H:%M:%S'`
$inputfilelist=myinputfilelist.txt
for file in $(<$SOURCEDIR/$inputfilelist)
do
if [[ $file == "#"* ]];
then
echo "Moving of $file ignored"
else
starttime=`date +'%Y-%m-%d %H:%M:%S'`
echo "Starting moving $file at $starttime......"
mv $file /targetfiledirectory/
echo "$file moved to target directory"
fi
done
3) To check number of parameters sent to a script use the below commands in a script:
#!/usr/bin/ksh
if [[ $# -ne 1 ]]; then
echo "Invalid parameters.\nUsage: $0 <filelist>"
exit 1
fi
4) To import the variables defined in other file you can use the below commands at the beginning of the script:
. ./file.conf /* works on unix and import variables from file.conf */
source directory_path/file.conf /* works on linux and imports variable names from file.conf */
5) Usage of while statement in unix is shown below:#!/usr/bin/ksh
count=5 # Initialise count to 5
while [ $count -gt 0 ] # while count is greater than 0 do
do
echo "the value of count is $count"
count=$(expr $count -1) # decrement count by 1
done
6) Usage of string array in unix is shown below:
#!/usr/bin/ksh
namelist="Joe John Peter Tom Bill"
for name in $namelist
do
if [ "$name" = "Joe" ]
then
echo "My name is $name"
else
echo "My other names are ${name}s"
fi
done
7) Usage of case statement in unix is shown below:
#!/usr/bin/ksh
case $1 #value from first parameter
in
1) echo 'One';;
2) echo 'Two';;
*) echo 'Three';;
esac
No comments:
Post a Comment