使用 bash 通过 getopts 调用不同的函数

calling different functions with getopts using bash

我正在尝试研究如何在一个脚本中拥有多个函数并选择带有参数的函数。问题似乎是,如果我选择一个函数,optarg 似乎与脚本不 运行。 在这个例子中,我会 运行 这样的脚本 ~# ./script.sh -a -c wordlist.txt 仅 运行 具有所选单词列表的第一个函数 与...一样 ~# ./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

解析命令行参数时,不要试图立即对它们采取行动。简单地记住你所看到的。 解析完所有选项后,您可以根据所学采取行动。

注意onetwo可以用程序参数化的单个函数(wgetcurl)替换为运行;当你这样做时,也将单词列表作为参数传递。

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

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

get_it "$getter" "$wordlist"