getopts 获取同一参数的多个值

发布于 2025-01-19 03:10:01 字数 735 浏览 2 评论 0原文

我希望使用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

I am looking to get multiple values from same argument using getopts. I want to use this script to ssh and run commands on a list of hosts provided through a file.

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

Expected output:

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

Sample Code I used but failed to get expected results



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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雪花飘飘的天空 2025-01-26 03:10:01

您可以通过重复-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"

You can achieve the effect by repeating -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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文