【发布时间】:2018-05-24 14:22:16
【问题描述】:
到目前为止,我的代码将从 iOS 系统获取 IP 地址和十六进制形式的子网掩码 (ffffff00),但我需要位形式(24、23 等)或二进制形式的子网地址。我该怎么做?我尝试使用16#${subnet} 转换它,但数字似乎错误。
有点愚蠢的问题——如果echo "hello" 行被删除并且我不确定为什么,代码不会运行?那条线起什么作用?
if [ $# -ne 0 ]
echo "hello"
then
ip="$(ifconfig | grep "inet " | grep -v 127.0.0.1 | cut -d\ -f2)"
subnet="$(ifconfig | grep "netmask " | grep -v 0xff0 | sed -e 's/.*0x\(.*\)broadcast.*/\1/')"
consub="$((16#${subnet}))"
echo "$ip $subnet $consub"
exit 0
fi
【问题讨论】:
-
if (condition) ; then是常用语法。 echo 是一个语句,允许您出于愚蠢的原因跳过;。 -
另外,如果您正在编写不需要 POSIX 可移植性的 bash 脚本,请考虑使用
[[ .. ]]而不是[ .. ]。 -
@hack,你能不能add to your question 你得到的结果,以及你想看到的结果?这将有助于评估我们为创建答案所做的工作。你的问题是一个很好的开始。如果它包含MCVE,那就更好了。
标签: bash ip-address subnet