bash shell脚本,32位十进制到二进制转换器的问题

时间:2016-05-06 04:04:23

标签: bash shell math binary decimal

遇到问题 当我运行它时,控制台一遍又一遍地重复这个;

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

与上述相同,但有解释权。

#!/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./

1 个答案:

答案 0 :(得分:2)

您的脚本有几个问题。这个没有任何错误。

#! /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=$((2 ** $exp))
    exp=$(expr $exp - 1)
    if (( bit+num  < user ))
    then
      ipb="${ipb}1"
      num=$(expr $num + $bit)
    else
      ipb="${ipb}0"
fi
done
echo $ipb
echo "done"
fi

一个主要问题是expr无法计算权力。当您尝试将expr的结果分配给变量时,也不要使用命令替换 另一个主要问题是,当您尝试在if分支中执行时,不能在单个[ ]括号内进行数学运算。请改用(( )) 还有一些其他问题,例如$ipb="${ipb}1"扩展您实际想要分配的变量。