Error when running script involving machine name and local network

Hi everyone, I'm trying to write a script that takes a machine name as a command line argument and displays a message informing me whether the host is on the local network.

Here's what I have:

#!/bin/bash
gateway=$(ip route | grep default | cut -d' ' -f3)

if [[ $(ip route get "$1" | grep -q $gateway) ]]; then

echo "$1 is on the local network"

else

echo "$1 is not on the local network"

fi

Whenever I run it with my machine name (ubuntu) I get the following output:

Error: any valid prefix is expected rather than "ubuntu".
ubuntu is not on the local network

I'm not sure what the error means and why I'm getting it, as well as if the script is even doing what it should be doing. Any advice would be appreciated. Thanks!

  1. insert set -x after the first line of your script, run it and check the different commands and if they do, what you are expect them to do.
  2. run the commands one by one and later combined as up to the version in your script and check if the commands do what you expect them to do
  3. insert echo statements in your script, which show the variables to make sure the values are like desired
  4. use quoting to avoid surprises:
    text # not this gateway=$(iproute | grep | zip | cat | ...) # but this gateway="$(iproute | grep | zip | cat | ...)"