【发布时间】:2016-09-01 00:50:07
【问题描述】:
对此有疑问 当我运行它时,控制台会一遍又一遍地重复;
14: shellscript.sh: 2: not found
15: shellscript.sh: 32: not found
18: shellscript.sh: =1: not found
19: shellscript.sh: 0: not found
好像和bash如何通过算术处理重定义变量有关?
#!/bin/bash
echo "This script converts a user's number into an IP address."
echo -n "Input your number: "
read user
if [ $user -lt 4294967296 ]
then
exp=$((32))
num=$((0))
ipb=""
while [ $exp -gt 0 ]
do
bit=expr 2 ** $exp
exp=expr $exp - 1
if [ $bit+$num -le $user ]
then
$ipb="${ipb}1"
num=expr $num + $bit
else
$ipb="${ipb}0"
fi
done
echo $ipb
echo "done"
fi
同上,但用 cmets 来解释。
#!/bin/bash
echo "This script converts a user's number into an IP address."
echo -n "Input your number: "
read user
#check if number is larger than 32bits
if [ $user < 4294967296 ]
then
#var exp is exponent that will be used to redefine var bit each loop cycle
#var num is var used to rebuild the user number with corresponding bits added to -
#var ipb is IP binary (not yet converted to 4 octet integers)
exp=$((32))
num=$((0))
ipb=""
#while the exponent is greater than 0 (exponent is 1 less as per binary order)
while [ $exp > 0 ]
do
#(Re)define bit var for line 23
bit=expr 2**$exp
#go to next lowest exponent
exp=expr $exp - 1
#If the current bit is added to our num var,will it be
#less than or equal to the user number?
if [ $bit + $num -le $user ]
then
#If so, redefine the ipb string var with a 1 on the end
#and redefine the num integer var added with the current
#iteration of the bit integer var's value
$ipb="${ipb}1"
num=expr $num + $bit
else
#if not, redefine the ipb string var with a 0 on the end
$ipb="${ipb}0"
fi
done
#output the IP binary
echo $ipb
echo "done"
fi
编辑:
经过一番谷歌搜索和 shellcheck 的帮助后,我让它工作了。出于某种原因,对于我的 linux mint 版本,let 命令是唯一正确地将2**31 作为指数运算的东西。这是任何好奇的人的代码。
echo "This script converts a user's number into the 32 bit equivalent."
echo -n "Input a number below 4294967296: "
read user
echo ""
if [ $user -lt 4294967296 ]
then
exp=$((31))
num=$((0))
ipb=""
while [ $exp -ge 0 ]
do
let bit=2**$exp
let exp-=1
if (( $bit + $num <= $user ))
then
ipb="${ipb}1"
num=$(($num + $bit))
else
ipb="${ipb}0"
fi
done
fi
echo $ipb
在终端中运行脚本时,请务必使用bash 而不是sh 或./。
【问题讨论】:
-
请尝试根据shellcheck.net 的建议修改您的脚本,然后看看问题是否仍然存在..
-
if [ $bit + $num -le $user ]所以你知道数字比较是用-le / -ge完成的(虽然if条件本身还是错误的......)&你仍然使用while [ $exp > 0 ]?
标签: bash shell math binary decimal