Friday, April 1, 2016
Linux Bash Shell Script Function Argument Passing Examples
April 01, 2016
argument passing
,
beginner
,
code
,
directory listing
,
easy
,
explanation
,
folder recusive
,
function parameter passing
,
linux
,
recursive directory traversal
,
regex
,
regular expression
,
script
,
shell
,
tutorial
Code Function Argument To Read Argument File From Terminal line by line:
Save the code in a file named "FunctionArgumentPassing1.sh".
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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".
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Code Function Argument Traverse Directories Recursively:
Save the code in a file named "FunctionArgumentPassing2.sh".
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment