我有一些用户提供的IP地址:
192.168.50.$i
现在我希望+200
使用$i
。因此,如果用户执行:
bash script 52 20 56
结果必须是
ping 192.168.50.252 , ...
我想做点什么:
function
{
$i = $i + 200
ping 192.168.50.$i
}
当它高于255时,我该怎么办?
答案 0 :(得分:1)
你可以这样做......
echo "192.168.50.$(( $i + 200 ))"
如果你想检查它是否大于255,你将不得不将其分解。
fourth=$(( $i + 200 ))
if (( fourth > 255 ))
then
echo "Greater than 255!"
exit 1
fi
问题变更 没有看到最后一部分
你可以创建一个函数,但这不会起作用,因为语法已经解决了。
function
{
$i = $i + 200
ping 192.168.50.$i
}
你需要做这样的事情......
# Function name
function ip_assess {
# $1 takes the first input to the function
# There is no $ when assigning to a variable
# There is no spaces around the = when assigning
i=$(( $1 + 200 ))
# No need for $ when doing arithmetic comparisons
if (( i > 255 ))
then
# Return an error code of 1 from this function
return 1
fi
# -c 4 will get it to ping four times and return and not continuously
# If the ping is a success return 0 (a pass). If no then 2 (different error code)
ping "192.168.50.$i" -c 4 && return 0 || return 2
}
ip_assess 30
# Grab the error code
valid_ip=$?
case $valid_ip in
0 )
echo "Valid IP"
;;
1 )
echo "IP is to high"
;;
2 )
echo "IP not alive"
;;
esac