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

问题描述 投票:0回答:1

我试图找出如何在一个脚本中拥有多个函数并选择带参数的函数。似乎问题是,如果我选择一个函数,optarg似乎不会与脚本一起运行。在这个例子中,我将运行脚本〜#。/ script.sh -a -c wordlist.txt,只运行第一个函数,其选择与〜#。/ 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
bash sh getopts
1个回答
4
投票

解析命令行参数时,请勿尝试立即对其执行操作。只记得你所看到的。解析完所有选项后,您可以根据所学内容采取措施。

请注意,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"
© www.soinside.com 2019 - 2024. All rights reserved.