Reputation: 6725
Hello I was wondering what would be the best way break this block of code into functions and
case $# in
1) ports='1-1023'
host=$1 ;;
2) ports=$1
host=$2 ;;
*) echo 'Usage: portscan [port|range] host'
exit 1 ;;
esac
# check port range
if [ "$(echo $ports | grep '^[1-9][0-9]*-[1-9][0-9]*$')" != "" ]; then
firstport=$(echo $ports | cut -d- -f1)
lastport=$(echo $ports | cut -d- -f2)
elif [ "$(echo $ports | grep '^[1-9][0-9]*$')" != "" ]; then
firstport=$ports
lastport=$ports
else
echo "$ports is an invalid port(s) value"
exit 2
fi
# check firstport > lastport
if [ $firstport -gt $lastport ]; then
echo $firstport is larger than $lastport
exit 3
fi
**and call them in main like this****
# Check parameters and exit 1 if problem
check_parms $#
# Check port range and exit 2 if problem
check_ports $ports
# Check port order and exit 3 if problem
check_order $firstport $lastport
Upvotes: 0
Views: 84
Reputation: 4559
When you call a bash function, it too has its own $*, $#, $1, .... to reflect that invocation. So you could build a bunch small functions like
function check_parms() {
local num=$# <----------- I changed this line
case $num)
... etc
}
and then,
function check_ports() {
local ports=$1
if ...
}
etc.
I hope this gives you some ideas for refactoring. In case you were thinking of source
ing the bash script, a good idea might be to unset
the functions that you defined at the end of the script.
A nice tutorial at here
In the main block, call it like any other bash function. For example:
echo "hello"
check_parms $*
check_ports $ports
echo "..."
Upvotes: 1