I'm trying to learn how to write Bash scripts. I have this script to update my servers through ssh. I'm trying to add a check and a conditional to determine if the OS uses Yum or Apt then it will run the appropriate update commands. The if else statement seems to be wrong but I'm not sure how to correct this.
Here is the script:
#!/bin/bash
USERNAME="root"
HOSTS="host1 host2 host3"
apt_run="apt update && apt -y upgrade"
yum_run="yum check-update && yum -y update"
for HOSTNAME in ${HOSTS} ; do
ssh -l ${USERNAME} ${HOSTNAME}
find_os=$( command -v yum || command -v apt-get ) || echo "Neither
yum nor apt-get found"
if [[ $find_os='yum' ]]
then
"${yum_run}"
else
"${apt_run}"
fi
done
"Neither yum nor $? Seems its too long and cut off by an editor.[[ $find_os == 'yum' ]]or probably more accurately (becausecommand -v yumon my workstations returns/usr/bin/yum):[[ "${find_os##*/}" == yum ]]ssh -l ${USERNAME} ${HOSTNAME} <there is no command here>. The syntax isuser@host...apt_runandyum_run) has severe problems (see BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!). Using it withsshmight actually work, because the oddities ofsshcommand parsing might cancel out those of variable expansion... sort of. Maybe. But IMO it's better to avoid the additional source of confusion, and just use commands directly wherever possible.