getopts 为同一个参数获取多个值

getopts to get multiple values for same argument

我希望使用 getopts 从同一个参数中获取多个值。我想使用此脚本对通过文件提供的主机列表执行 ssh 和 运行 命令。

用法:.\ssh.sh -f file_of_hosts.txt -c "Command1" "command2"

预期输出:

ssh userid@server1:command1
ssh userid@server1:command2
ssh userid@server2:commnand1
ssh userid@server2:commnand2

示例代码我用了但是没有得到预期的结果



id="rm08397"
while getopts ":i:d:s:f:" opt
   do
     case $opt in
        f ) file=$OPTARG;;
        c ) cmd=$OPTARG;;
     esac
done
shift "$(($OPTIND -1))" 
# serv=$(for host in `cat $file`
# do 
#     echo -e "$host#"
# done
# )

# for names in $serv
# do 
#     ssh $id@$serv: 


for hosts in $file;do
   for cmds in $cmd;do
      o1=$id@$hosts $cmds
      echo $o1
   done   
done

重复-c:

即可达到效果
declare -a cmds
id="rm08397"
while getopts ":c:f:" opt
   do
     case $opt in
        f ) file="$OPTARG";;
        c ) cmds+=("$OPTARG");;
     esac
done
shift $((OPTIND -1)) 

for host in $(<$file);do
   for cmd in "${cmds[@]}";do
      echo ssh "$id@$host" "$cmd"
   done   
done

# Usage: ./ssh.sh -f file_of_hosts.txt -c "Command1" -c "command2"