0

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
Noah
  • 35
  • 4
  • `getopts` doesn't support this format directly. – Barmar Apr 04 '22 at 20:03
  • Going further off-topic, you might want to look at something like Ansible. There are already lots of tools for doing things like this without needing to reimplement them from scratch. – chepner Apr 04 '22 at 20:10
  • Thanks @barmar I will look for other options to fix this issue – Noah Apr 04 '22 at 20:25

1 Answers1

1

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"
Philippe
  • 20,025
  • 2
  • 23
  • 32