0

suppose I have a script like so: (let's call it test.sh)

#!/bin/sh

function php() {
    printf "The rhost is ${RHOST} and the lport is ${LPORT}"
}

while getopts "hr:l:s:" arg; do
    case $arg in
        h)
            printf "Usage\n"
        ;;

        r)
            RHOST=$OPTARG
        ;;

        l)
            LPORT=$OPTARG
        ;;

        s)
            SHELL=$OPTARG

            if [[ "$SHELL" == "php" ]] || [[ "$SHELL" == "PHP" ]] ; then
                php

            fi
       ;;
    esac
done

If I run my script like "test.sh -r 10 -l 4 -s php"

My script will perform like I want...

However, if I run it like "test.sh -s php -r 10 -l 4"

rhost and lport variables never make it to the php function. I realize this is because it's being called first. However, my question is, how can I write the script, so that no matter the order of the way the arguments are run, I can still use rhost and lport as variables?

I have also tried playing with shift, but I am guessing that is not the answer or I am placing the shift command in the wrong spot.

DFC302
  • 17
  • 1
  • 6
  • Don't use all upper case for non exported variable names so you avoid clashing with the exported variables (as `SHELL` is doing currently in your script). See https://stackoverflow.com/q/673055/1745001 – Ed Morton Jul 03 '19 at 13:57
  • 1
    Ok I will make those corrections. Thankyou for the advice! I apperciate it. – DFC302 Jul 03 '19 at 14:02
  • Also, you can assign the variable to the lower-cased value: `shell=${OPTARG,,}` then your `if` condition is simpler: `if [[ $shell == php ]]; then ....` -- see [3.5.3 Shell Parameter Expansion](https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion) – glenn jackman Jul 03 '19 at 14:41

1 Answers1

4

Move the "if" logic out of the switch/case:

#!/bin/sh
function php() {
    printf "The rhost is ${RHOST} and the lport is ${LPORT}"
}

while getopts "hr:l:s:" arg; do
    case $arg in
        h)
            printf "Usage\n"
        ;;

        r)
            RHOST=$OPTARG
        ;;

        l)
            LPORT=$OPTARG
        ;;

        s)
            SHELL=$OPTARG         
       ;;
    esac    
done

if [[ "$SHELL" == "php" ]] || [[ "$SHELL" == "PHP" ]] 
then
   php
fi
Erez Ben Harush
  • 833
  • 9
  • 26