Shell脚本在控制台中工作,但在保存为文本文件时不起作用

Jol*_*oly 3 shell cygwin newline

考虑这个简单的shell脚本:

#!/bin/sh
fruitlist="Apple Pear Tomato Peach Grape"
for fruit in $fruitlist
do
   if [ "$fruit" = "Tomato" ] || [ "$fruit" = "Peach" ]
   then
      echo "I like ${fruit}es"
   else 
      echo "I like ${fruit}s"
   fi
done
Run Code Online (Sandbox Code Playgroud)

当我将它粘贴到cygwin窗口时,它工作正常但是当我将其保存为文本文件test.sh并从cygwin终端运行时我得到了这个:

$ ./test.sh
./test.sh: line 4: syntax error near unexpected token `$'do\r''
'/test.sh: line 4: `do
Run Code Online (Sandbox Code Playgroud)

但是,如果我删除换行符,它会起作用:

#!/bin/sh
fruitlist="Apple Pear Tomato Peach Grape"
for fruit in $fruitlist
do if [ "$fruit" = "Tomato" ] || [ "$fruit" = "Peach" ]
   then echo "I like ${fruit}es"
   else echo "I like ${fruit}s"
fi done
Run Code Online (Sandbox Code Playgroud)

如何通过在文件中维护新行来使脚本更具可读性,\n似乎不起作用.

fed*_*qui 5

您的\r角色来自Windows文件,其中定义了新行\r\n.在UNIX中,新行被定义为\n,因此\r保持"孤儿"并导致这些问题.

您可以做的是使用该命令将文件转换为UNIX模式dos2unix.

更多信息:Windows回车\ r \n是由两个字符还是一个字符组成?:

两个字符组合在一起表示Windows上的新行.而在Linux上,\n代表新线.它将光标移动到Linux上新行的开头.在Windows上,光标将保留在控制台中的同一列,但在下一行.

  • \r 是回车;
  • \n 是换行.