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

0 bash sh getopts

我想弄清楚如何在一个脚本中拥有多个函数并选择带有参数的函数。问题似乎是,如果我选择一个函数,optarg 似乎不会与脚本一起运行。在这个例子中,我会这样运行脚本 ~# ./script.sh -a -c wordlist.txt 只运行第一个函数,选择的 wordlist 与 ~# ./script.sh -b -c wordlist 相同。文本

#!/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
Run Code Online (Sandbox Code Playgroud)

che*_*ner 5

在解析命令行参数时,不要试图立即对它们采取行动。只需记住你所看到的。之后您已经解析所有的选项,你可以根据你所学到的东西采取行动。

请注意,onetwo可以替换为由程序(wgetcurl)参数化的单个函数来运行;在此过程中,也将单词列表作为参数传递。

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"
Run Code Online (Sandbox Code Playgroud)