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
3
  • getopts doesn't support this format directly. Commented Apr 4, 2022 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. Commented Apr 4, 2022 at 20:10
  • Thanks @barmar I will look for other options to fix this issue Commented Apr 4, 2022 at 20:25

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Philippe. This seems to be working. Appreciate your response

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.