Fun with Bash Scripting

Bash Scripting , I recently came across a situation where i had to perform certain task on a random file ( of particular extension ) picked up from a directory structure. My OS was linux and so i went for Bash Scripting !

The script informs the performers what they are supposed to say and do in Bash Scripting. computer script informs the pc what it could or should say.We’re telling the Bash shell what to do in  the framework of Bash scripts. A Bash script is a plain text file containing a number of commands.

I played with some known ( to me, obviously ) commands from my PS1 prompt before i nailed it down.

SearchFolder=”/home/sai/cPrograms”
NumberOfcFiles=`find $SearchFolder -iname “*.c” | wc -l`
rNumber=$[ ( $RANDOM % $NumberOfcFiles ) + 1 ]
rFile=`find $SearchFolder -iname “*.c” | sed -n “$rNumber p”`
ls $rFile

Line by Line Logic

SearchFolder=”/home/sai/cPrograms”

This sets the parent folder of the directory tree to be searched, i.e the scan starts from this directory and prgresses inward for Bash Scripting.

NumberOfcFiles=`find $SearchFolder -iname “*.c” | wc -l`

Variable NumberOfcFiles speaks for itself. find makes a list of .c files and “wc -l” counts them for me.

rNumber=$[ ( $RANDOM % $NumberOfcFiles ) + 1 ]

$RANDOM is a bash variable that throws pseudo random numbers every time its called ( Thanks to BASH again ! ). RightHandSide of the above code is to obtain a random number within the 1-$NumberOfcFiles range. i.e if there are 100 files, rNumber will be a random number with in the range 1 – 100.

rFile=`find $SearchFolder -iname “*.c” | sed -n “$rNumber p”`
ls $rFile

This simply picks $rNumber th file from the “find” list and ls prints it on your screen.

Wasn’t that fun ??

go for quick reference on click here

reference sites :wikipedia

Leave a Reply

Your email address will not be published. Required fields are marked *