如何在shell脚本的if/else语句中正确嵌套循环?
我在Linux中有以下代码:如何在shell脚本的if/else语句中正确嵌套循环?,sh,Sh,我在Linux中有以下代码: #!/bin/sh echo "Enter a number:"; read n; if (($# != 0)) for ((i=1; i< $n+1; i++)) do echo $i done else for ((i=1; i<21; i++)) do echo $i done fi #/垃圾箱/垃圾箱 echo“输入一个数字:”;读n; 如果($#!=0)) (i=
#!/bin/sh
echo "Enter a number:"; read n;
if (($# != 0))
for ((i=1; i< $n+1; i++))
do
echo $i
done
else
for ((i=1; i<21; i++))
do
echo $i
done
fi
#/垃圾箱/垃圾箱
echo“输入一个数字:”;读n;
如果($#!=0))
(i=1;i<$n+1;i++)
做
回声$i
完成
其他的
对于((i=1;i您缺少一个then
。此外,正如其他人所提到的,您的实现是bashism,因此请注意对第一行的更改
#!/bin/bash
echo "Enter a number:"; read n;
if (($# != 0))
then
for ((i=1; i< $n+1; i++))
do
echo $i
done
else
for ((i=1; i<21; i++))
do
echo $i
done
fi
!/bin/bash
echo“输入一个数字:”读取n;
如果($#!=0))
然后
(i=1;i<$n+1;i++)
做
回声$i
完成
其他的
对于((i=1;i您缺少一个then
。此外,正如其他人所提到的,您的实现是bashism,因此请注意对第一行的更改
#!/bin/bash
echo "Enter a number:"; read n;
if (($# != 0))
then
for ((i=1; i< $n+1; i++))
do
echo $i
done
else
for ((i=1; i<21; i++))
do
echo $i
done
fi
!/bin/bash
echo“输入一个数字:”读取n;
如果($#!=0))
然后
(i=1;i<$n+1;i++)
做
回声$i
完成
其他的
对于((i=1;i您缺少,然后:
if (($# != 0)) ; then
您丢失了,然后:
if (($# != 0)) ; then
实际适用于所有/bin/sh
实现的代码版本可能如下所示:
#!/bin/sh
echo "Enter a number:"; read n;
if [ "$#" -ne 0 ]; then
i=0; while [ "$i" -lt $(( n + 1 )) ]; do
echo "$i"
i=$((i + 1))
done
else
i=0; while [ "$i" -lt 21 ]; do
echo "$i"
i=$((i + 1))
done
fi
注意if
构造有效所需的then
;将if(…)
更改为if[…]
;将((;;;))更改为)
到循环进行计数。实际适用于所有/bin/sh
实现的代码版本可能如下所示:
#!/bin/sh
echo "Enter a number:"; read n;
if [ "$#" -ne 0 ]; then
i=0; while [ "$i" -lt $(( n + 1 )) ]; do
echo "$i"
i=$((i + 1))
done
else
i=0; while [ "$i" -lt 21 ]; do
echo "$i"
i=$((i + 1))
done
fi
注意if
构造有效所需的then
;将if(…)
更改为if[…]
;将(;;)
更改为while
循环进行计数。您的缺失也可以在将来帮助您。“shell”不是指定的环境。请使用正确的shell对此进行标记。此外,请检查标记的说明。另外两个标记不仅没有帮助,而且完全错误。for((…)
是一种Bash主义。/bin/sh
实现不一定支持它。现在需要/bin/sh
的情况也很少见。如果您试图编写Bash,请使用/bin/Bash
。您所缺少的功能在将来也会对您有所帮助。“shell”不是指定的环境。请使用正确的shell对此进行标记。此外,请检查标记的说明。另外两个标记不仅没有帮助,而且完全错误。for((…)
是一种Bash主义。/bin/sh
实现并不一定支持它。现在需要/bin/sh
的情况也非常罕见。如果您试图编写Bash,请使用/bin/Bash
。即使如此,此代码也与POSIX sh不兼容;用于((i=1;iAgreed。这只是为了修复他预期实现中的语法错误。也许您应该将shebang更改为#!/bin/bash
?即使如此,此代码也与POSIX sh;不兼容((i=1;iAgreed。这只是为了修复他预期实现中的语法错误。那么,您是否应该将shebang更改为#!/bin/bash
?