Friday, April 1, 2016

Linux Bash Shell Script Function Argument Passing Examples


Code Function Argument To Read Argument File From Terminal line by line:

Save the code in a file named "FunctionArgumentPassing1.sh".
#!/bin/bash
readFile(){
while read line
do
echo $line
done < "$1"
}
readFile log.txt

Running the Code:

Just type the code below in terminal. Make sure to cd into that directory if you have not opened the terminal in that directory. Make sure to create the "log.txt" file in the same directory as the shell script file.

bash FunctionArgumentPassing1.sh

Sample Input File:

Save as "log.txt".
192.1.4.09 10:30 Arsenal
110.13.5.67 5:12 Chelsea
192.1.45.67 23:21 Man United
199.13.8.23 8:33 Man city
172.11.22.2 18:45 Arsenal
133.13.8.23 10:00 Moon colony
112.11.22.2 8:00 Mars colony
103.13.8.23 9:00 Jupiter colony
12.11.22.2 8:59 Europa colony
view raw log.txt hosted with ❤ by GitHub

Code Function Argument Traverse Directories Recursively:

Save the code in a file named "FunctionArgumentPassing2.sh".
#!/bin/bash
#Recursively traverse the directories
traverseDirectory(){
for fileName in `ls $1/`
do
if [ -d $1/$fileName ]; then
echo "$1/$fileName"
traverseDirectory "$1/$fileName"
#rm -rf $1/$fileName
fi
done
}
var='deletefolder'
traverseDirectory $var

Running the Code:

Just type the code below in terminal. Make sure to cd into that directory if you have not opened the terminal in that directory. Make a directory named "deletefolder" with more directories inside and inside them some files.

bash FunctionArgumentPassing2.sh

No comments: