Search code examples
bashshellgetopts

Trying to save an argument as a variable in bash script


I am trying to save the argument after "-ip" as a variable in the bash script:

if [ $# == 0 ]; then
        ARGS=""
else
        for var in "$@"
        do
                ARGS="$ARGS $var"
                if [ $var == "-ip" ];   then
                        getopts ip: $IP
                fi
        done
fi

echo $IP

I never tried 'getopts' in bash, I tried the first time as you can see above and failed literally.

Any help would be very appreciated,

Thanks


Solution

  • You can avoid getopts all together and just grab it with a regex.

    myvar=$(echo "$@" | sed 's/.*-ip\s\+\([0-9a-zA-Z\.]\+\)\s*.*/\1/g')
    

    Loads whatever is after -ip into myvar. Adjust the regex accordingly if you only want something that will match an IP.