我试图弄清楚如何在一个脚本中具有多个功能并选择带有参数的功能。问题似乎是,如果我选择一个函数,则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
答案 0 :(得分:4)
解析命令行参数时,请勿尝试立即对其进行操作。只需记住您所看到的。 分析完所有选项后,您可以根据所学知识采取行动。
请注意,one
和two
可以由程序(wget
或curl
)参数化的单个函数来运行;在使用它时,也将单词列表作为参数传递。
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"