0

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

Gerald
  • 83
  • 8
  • Have you tried reading the description of `getopts` in `man bash` or `help getopts`? – choroba Mar 29 '19 at 14:15
  • There are tons of examples here. Keep searching. – glenn jackman Mar 29 '19 at 14:16
  • 2
    Notice that `getopts` supports only single-letter options. – Benjamin W. Mar 29 '19 at 14:22
  • since getopts only supports single-letter options, would someone have any other options on this bash script? thanks ! – Gerald Mar 29 '19 at 14:33
  • 1
    Don't collect the arguments in a regular parameter like `ARGS`. If `ARGS` contains `foo bar`, you can't tell if that was one single argument `foo bar` or two separate arguments `foo` and `bar`. – chepner Mar 29 '19 at 14:45
  • See: [How do I parse command line arguments in Bash?](https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash) – Gordon Davisson Mar 29 '19 at 14:57

1 Answers1

1

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.

jasonmclose
  • 1,667
  • 4
  • 22
  • 38
  • I would *not* recommend using this -- it mashes all the arguments into a single string, and looks for "`-ip `" anywhere in it. But that could be in the middle of an argument (spaces are legal -- and even normal -- in arguments), at the end of an argument (say you have a file named "servers-by-ip" -- this'll mistake the "-ip" part for a flag). – Gordon Davisson Mar 29 '19 at 19:04