0

I am trying to work out how i can have multiple functions in one script and choose the function with an argument. what seems to be the issue is that if i choose a function the optarg does'nt seem to be run with the script. in this example I would run the script as such ~# ./script.sh -a -c wordlist.txt that to only run the first function with the wordlist of choice same as ~# ./script.sh -b -c wordlist.txt

#!/bin/bash

one()
{
for i in $(cat $wordlist); do
  wget http://10.10.10.10/$i
}

two()
{
for i in (cat $wordlist); do
  curl http://10.10.10.10/$i
}

while getopts "abc:" option; do
 case "${option}" in
    c) wordlist=${OPTARG} ;;
    a) one;;
    b) two;;
  esac
done
6
  • 2
    You’re missing a couple of dones. Commented Mar 6, 2019 at 16:02
  • i am this was just an example not the actual script im having trouble with. Commented Mar 6, 2019 at 16:05
  • 1
    If I understand the issue correctly, and I’m not sure I do, it’s because you run ./script.sh -a -c wordlist.txt, which causes getopts to call see -a before -c, which causes one to be called before wordlist is asssigned. So either run ./script.sh -c wordlist.txt -a or make sure to call one (or two) after the while loop. Commented Mar 6, 2019 at 16:12
  • 1
    Your case statement shouldn't actually do much, if any, actual work. Its job is to simply recognize and remember which options were seen. After the loop is the right time to perform any actions, once you have all the information available. Commented Mar 6, 2019 at 16:13
  • @Biffen it works if i add the -a after like you said. so thankyou!!! awesome ! Commented Mar 6, 2019 at 16:18

1 Answer 1

5

When parsing command-line arguments, don't try to act on them immediately. Simply remember what you have seen. After you have parsed all the options, you can take action based on what you have learned.

Note that one and two can be replaced by a single function parameterized by the program (wget or curl) to run; while you are at it, pass the word list as an argument as well.

get_it () {
    # $1 - program to run to fetch a URL
    # $2 - list of words to build URLs
    while IFS= read -r line; do
        "$1" http://10.10.10.10/"$line"
    done < "$2"
}

while getopts "abc:" option; do
 case "${option}" in
    c) wordlist=${OPTARG} ;;
    a) getter=wget;;
    b) getter=curl;;
  esac
done

get_it "$getter" "$wordlist"
Sign up to request clarification or add additional context in comments.

1 Comment

@m4lvo, left as an exercise is to validate that the user actually provided a valid wordlist file, and the user selected either -a or -b.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.