jimmaJAMES
jimmaJAMES

Reputation: 23

Ignoring bash variables

I'm working on creating a basic port scanner and have the scanner functioning, but I am struggling with adding a function that adjusts the timeout feature. How can I get bash to notice that $1 and $2 are not there and to proceed with reading $3 $4 $5 in the command line input? This is what I have so far

#!/bin/bash

changetime=$1
newtime=$2
host=$3
startport=$4
stopport=$5

if [ $1 = "-t" ]
then
    timeout "$newtime"
    echo "Timeout changed to $newtime second(s)."
else
    $changetime=0
    $newtime=0
fi

I'm able to get the scanner to work if I enter the bash command

./portscanner.sh -t 3 www.google.com 79 81

but bash does not like anything that I put after the else

Upvotes: 2

Views: 148

Answers (1)

John1024
John1024

Reputation: 113824

Try:

#!/bin/bash

if [ $1 = "-t" ]
then
    changetime=$1
    newtime=$2
    #timeout "$newtime"
    echo "Timeout changed to $newtime second(s)."
    shift 2
else
    changetime=0
    newtime=0
fi

host=$1
startport=$2
stopport=$3

echo "newtime=$newtime host=$host startport=$startport stopport=$stopport"

For example:

$ ./portscanner -t 3 www.google.com 79 81
Timeout changed to 3 second(s).
newtime=3 host=www.google.com startport=79 stopport=81
$ ./portscanner www.google.com 79 81
newtime=0 host=www.google.com startport=79 stopport=81

The key change here is the addition of shift. We can see how shift operates on the parameters with this command line example:

$ set -- 1 2 3 4
$ echo "$@"
1 2 3 4
$ shift 2
$ echo "$@"
3 4

Thus, shift 2 removes the first two parameters, leaving the remaining ones (which are now renumbered to start again with $1).

Upvotes: 3

Related Questions