I am trying to make a simple bash script to check if a ping command could be executed (there is internet) or if not otherwise.
I already had a code which works perfectly which checked directly in the if statement if the ping command can be executed without making an output using /dev/null.
Old code:
#! /usr/bin/bash
YELLOW="\e[33m"
RED="\e[1;31m"
GREEN="\e[1;32m"
ENDCOLOR="\e[0m"
if ping -c 1 8.8.8.8 > /dev/null 2>&1; then
echo -e "${YELLOW}[*]${ENDCOLOR} You have Internet access."
else
echo -e "\n ${RED}[!]${ENDCOLOR} You don't have Internet access !"
echo -e "\n ${YELLOW}[*]${ENDCOLOR} Quitting webDirDiscover..."
exit 1
fi
Now what I want to do is store the command ping -c 1 8.8.8.8 in a variable called PING. Once this is done, execute the if statement and check the result.
The problem is that doing this returns the error:
./webDirDiscover.sh: line 10: PING: command not found
When I think that the if statement should work correctly.
Current code:
#! /usr/bin/bash
YELLOW="\e[33m"
RED="\e[1;31m"
GREEN="\e[1;32m"
ENDCOLOR="\e[0m"
PING=$(ping -c 1 8.8.8.8)
if $PING -eq 0; then
echo -e "${YELLOW}[*]${ENDCOLOR} You have Internet access."
else
echo -e "\n ${RED}[!]${ENDCOLOR} You don't have Internet access !"
echo -e "\n ${YELLOW}[*]${ENDCOLOR} Quitting webDirDiscover..."
exit 1
fi
In addition to solving this simple script, this will come in handy when executing more complex commands and thus have a more visual and visually pleasing code.