我正在尝试制作一个bash脚本 - 接收两个输入(只有两个) - 然后打印出两个数字之间的所有偶数 - 在任何可被7整除的数字旁边打印出橙色 - 在任何可被11整除的数字旁边打印出香蕉 - 在任何可被13整除的数字旁边打印出梨 最后打印出一个声明“水果的痴迷是什么?”
它在这个编译器中工作正常(http://www.compileonline.com/execute_bash_online.php) 但在Linux中它出现错误信息,说$ Input2不是公认的标识符,并且在最后一行之后有一个意外的文件结尾
#!/bin/bash
read -p "Type in Two integer inputs you want evaluated, followed by [ENTER]:" Input1 Input2
if [ -z $Input1 ]; then
echo "Please enter a valid first integer"
read -r Input1 Input2
exit 1
fi
if [ -z $Input2 ];
then
echo "Please enter a valid second integer"
read Input2
fi
if [ $# -gt 2 ]; then
echo "Too many numbers have been inputted"
fi
echo "You entered: $Input1,$Input2"
echo "Here are all the even numbers between your two values:"
echo ""
# if Input 1 is larger than Input 2
while [ $((Input2)) -lt $Input1 ]; do
if [ $((Input1 % 2)) -gt 0 ];then
echo -en "$((Input1 = $Input1 - 1)) "
else
echo -en "$((Input1 = $Input1 - 2)) "
fi
if [ $((Input1 % 7)) -eq 0 ]; then
echo -en "orange "
fi
if [ $((Input1 % 11)) -eq 0 ]; then
echo -en "banana "
fi
if [ $((Input1 % 13)) -eq 0 ]; then
echo -en "pear "
fi
echo
done;
while [ $((Input1)) -lt $Input2 ]; do
if [ $((Input2 % 2)) -gt 0 ];then
echo -en "$((Input2 = $Input2 - 1)) "
else
echo -en "$((Input2 = $Input2 - 2)) "
fi
if [ $((Input2 % 7)) -eq 0 ]; then
echo -en "orange "
fi
if [ $((Input2 % 11)) -eq 0 ]; then
echo -en "banana "
fi
if [ $((Input2 % 13)) -eq 0 ]; then
echo -en "pear "
fi
echo
done;
echo "what is with the fruit obsession?"
exit 0
答案 0 :(得分:1)
使用dos2unix
to convert windows样式的行终结符\r\n
来* nix样式\n
:
dos2unix fruit.sh
注意我在脚本上使用了反unix2dos
,然后当我运行它时,我得到了相同的错误:
$ ./fruit.sh Type in Two integer inputs you want evaluated, followed by [ENTER]:2 8 You entered: 2,8 Here are all the even numbers between your two values: 6 4 2 what is with the fruit obsession? $ unix2dos fruit.sh unix2dos: converting file fruit.sh to DOS format ... $ ./fruit.sh Type in Two integer inputs you want evaluated, followed by [ENTER]:1 2 ': not a valid identifier `Input2 ./fruit.sh: line 36: syntax error near unexpected token `done' '/fruit.sh: line 36: ` done; $
答案 1 :(得分:0)
此代码不仅更短且更易于阅读,而且还应该更快地运行。它的输出与原始脚本几乎相同,例外处理输入。
当我在Linux机器上测试它时,我不知道它是如何在cygwin下运行的。
#!/bin/bash
repeat=yes
while [ $repeat = "yes" ]; do
read -p "Type in Two integer inputs you want evaluated, followed by [ENTER]: " Input1 Input2 Input3
repeat=no
[ -z $Input2 ] && { echo "Incorect: Not Enough Inputs"; repeat=yes ;}
[ ! -z $Input3 ] && { echo "Incorect: Too many inputs"; repeat=yes;}
done
echo -e "You entered: $Input1,$Input2\nHere are all the even numbers between your two values:"
if [ $Input1 -lt $Input2 ]; then
larg=$Input1 ; small=$Input2
else
larg=$Input2 ; small=$Input1
fi
while [ $larg -lt $small ]; do
((small % 2)) && { echo ; echo -en "$((small = $small - 1)) " ;}
((small % 7)) || echo -en "orange "
((small % 11)) || echo -en "banana "
((small % 13)) || echo -en "pear "
small=$(($small - 1))
done
echo