Bash determine whether parameter variables ($1, $2, $3, etc.) have been set
2014-07
Many of the posts I just read have many answers that cover this, but I don't understand what I'm doing really; it's been hit & miss.
The .sh script I'm working with:
#!/bin/bash
# init
input=$1
output=$(ping -c 1 "$input" 2>/dev/null)
if [ $? -eq 0 ]; then
ip=$(printf '%s' "$output" | gawk -F'[()]' '/PING/{print $2}' 2>/dev/null)
echo "$ip";
sleep 2
else
echo "Host not found";
fi
Many of the posts I have just read cover this, and state there are several different methods that can be used to accomplish this, but I still don't really understand how to go about using them properly. Basically, I'm trying to check if the variable "$1" has been set by an argument, and display something like:
echo No argument given
if the variable is empty, instead of just pinging no host. My question is: How should I go about doing this without over-complicating things?
Help is always appreciated, thanks in advance.
PS: I'm still fairly new to linux environment, so go easy on me.
I'd add a check at the begining. In case of failure display a message and exit.
#!/bin/bash
# init
if [ -z "$1" ]; then
echo No argument given
exit
fi
input=$1
output=$(ping -c 1 "$input" 2>/dev/null)
if [ $? -eq 0 ]; then
ip=$(printf '%s' "$output" | gawk -F'[()]' '/PING/{print $2}' 2>/dev/null)
echo "$ip";
sleep 2
else
echo "Host not found";
fi
If you want to know the number of args passed, use $#. Like this:
if [ $# -eq 0 ]; then
echo "No argument given"
fi
Hope that helps.
Simply, whats the fundamental difference between $param
and ${param}
?
There is none. It's for echoing a variable immediately followed by a string.
For example, if you have $param, but you want to have right after it, "lbs"
echo "${param}lbs"
Where as
echo "$paramlbs"
Would look for an incorrect variable name