Shell 脚本整数输入

Shell script integer input

我的脚本有问题。我想要做的是根据在运行时输入脚本的整数值,它会在完成之前迭代文件转换拆分一定次数。我预见到的一个问题是,当 运行 通过脚本的 while 循环部分时,我将比较一个字符串而不是一个整数。这是一些代码。

    GTF=""
SP=$(dirname "$SCRIPT")

echo "Welcome to this script, Please do me a favor and enter the dimensions of the original Geographical Tiff file so I do not crash myself!!"

# Read the x axis max and y axis max so we do not have any errors.

echo "X axis -> "
read XMAX
echo "Y axis -> "
read YMAX

脚本中的 XMAX 和 YMAX 值必须是整数才能使其按预期工作。有人有解决方案吗?

谢谢!

您可以在 shell 中操作字符串,例如 bash ,就像 它们是整数一样。

如果您想在对其进行任何操作之前确保它是一个整数,您可以使用正则表达式来做到这一点,例如with:

echo -n "ENTER value: "
read xyzzy
if [[ ! $xyzzy =~ ^[0-9]+$ ]] ; then
    echo "No good"
    exit
fi
(( xyzzy = xyzzy + 1 ))
echo "Adding one gives" $xyzzy

这将确保数字仅由数字组成(如果您还想允许使用负整数,请使用 ^-?[0-9]+$):

pax$ testprog.sh
ENTER value: 5
Adding one gives 6

pax$ testprog.sh
ENTER value: x
No good

pax$ testprog.sh
ENTER value: x55y
No good

如果您使用的是不支持正则表达式相等性的非 bash shell,您可以调用外部程序,例如 grep 并检查其 return代码。

请记住,如果您使用 [[ 之类的东西将它们与其他值进行比较,请使用 -eq-ne-lt 及其兄弟比 ==!=.

后一组是字符串比较,前一组是数字比较。 bash 手册页对此进行了更深入的介绍。