robothead
robothead

Reputation: 323

SSH Bash script issues with if statement

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

Upvotes: 0

Views: 938

Answers (1)

Jetchisel
Jetchisel

Reputation: 7781

Here is my script for my virtual machines.

#!/bin/bash

hosts=(
  leap151 kali ubuntu omv
)

for hostname in "${hosts[@]}"; do
ssh -t root@"$hostname" << 'EOF'
  if type -P zypper >/dev/null; then
    command zypper ref && command zypper up
   elif type -P apt-get >/dev/null; then
     command apt-get update && command apt-get upgrade
  else
    echo 'Neither zypper nor apt found!' >&2
    exit 127
  fi
EOF
done

Use an array for the host. Since you're using bash the builtin type is fine just for searching the executable within your PATH. See help type for more info. Use the -t option in ssh also use a heredoc just what I have/did. The exit 127 is what the shell would exit if there are no executable see man 1p exit.

Upvotes: 2

Related Questions