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
CodePudding user response:
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"