Bash IF/ELIF statements

Viewed 40

So I am learning bash and wanted to make a script to 'automate' a collection of kali tools. Basically I do not understand why the if statement code is being triggered regardless if condition is true or false.

#!/bin/bash
#requires root or sudo priv

#check for a successful ping

target_ip=$1
nmap_opt = " "
#nmap options variables --
nmap_os="-O"
nmap_version="-sV"
nmap_udp="-sU"
nmap_stealth="-sS"
nmap_aggr="-A"
nmap_option_input_temp=""
ping $target_ip -c 5
if [ $? -eq 0 ]; then
        echo "successful ping on" $target_ip 
else
        echo "ping unsuccessful, check VPN connection or host may be down"
        exit 1
fi

read -p "enter pathway for nmap output: " nmap_file
read -p "detect os? (y/n) " nmap_option_input_temp

#add loops for y/n user input
if [[ ${nmap_option_input_temp} -eq "y" ]];
         then
                nmap_opt="${nmap_opt} ${nmap_os}"

elif [[ ${nmap_option_input_temp} -eq "n" ]];
         then
                nmap_opt=$nmap_opt
else
        echo "invalid option"  
fi

read -p "detect version? (y/n) " nmap_option_input_temp
#add loops for y/n user input
if [[ ${nmap_option_input_temp} -eq "y" ]];
                 then
                        nmap_opt="${nmap_opt} ${nmap_version}"

elif [[ ${nmap_option_input_temp} -eq "n" ]];
                 then
                        nmap_opt=$nmap_opt
else
        echo "invalid option"  
fi


echo "nmap selected option/s:" $nmap_opt
echo $nmap_option_input_temp
#starting nmap..
sudo nmap $nmap_opt -oN $nmap_file $target_ip 

this is the nmap_opt variable echo out even when both inputs are 'n'

nmap selected option/s: -O -sV

Let me know if there is anything I missed in the explanation!

1 Answers

-eq is for integer comparisons. Use ==:

if [[ "${nmap_option_input_temp}" == y ]];

And fix your quotes. Fixed strings like y don't need to be quoted. Inside [[, variables don't need to be quoted, but IMO you should quote them anyway for consistency.

This error would be more easily spotted if you used the more conventional:

if [ "${nmap_option_input_temp}" -eq y ];  # Still incorrect!!

since you would get a nice error message.

Note that the fix with [ is slightly different, and you should use a single =:

if [ "${nmap_option_input_temp}" = y ];

The == operator is a bashism which does not really add any value. But really, you should not be using if/elif at all here. This is the perfect place for a case statement:

case "${nmap_option_input_temp}" in
y) nmap_opt="${nmap_opt} ${nmap_os}";;
n) ;;
*) echo "invalid option" >&2 ;; 
esac
Related