Shell 脚本在控制台中有效,但在保存为文本文件时无效

标签 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

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

$ ./test.sh
./test.sh: line 4: syntax error near unexpected token `$'do\r''
'/test.sh: line 4: `do

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

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

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

最佳答案

您的 \r 字符来自 Windows 文件,其中新行用 \r\n 定义。在 UNIX 中,新行仅使用 \n 定义,因此 \r 保持“孤立”状态并导致这些问题。

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

更多信息:Does Windows carriage return \r\n consist of two characters or one character? :

Two characters combined represent a new line on Windows. Whereas on Linux, \n represents new line. It moves cursor to the start of new line on Linux. On Windows, the cursor will stay at the same column in the console but on the next line.

  • \r is carriage return;
  • \n is line feed.

关于Shell 脚本在控制台中有效,但在保存为文本文件时无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26216283/

相关文章:

bash - 你如何使用负偏移量在 bash 中获取字符串的后缀?

regex - 如何编写验证字母数字和空格的正则表达式

linux - 删除特定扩展文件格式以外的文件

c++ - 是否可以使用 Cygwin 或 MinGW 将 Linux 守护程序移植到 Windows?

windows - 是否可以通过 ssh 进入 Windows(通过 cygwin sshd)并在登录的 Windows 用户桌面上启动程序?

windows - 在 Windows 上将 GitHub 存储库下载为 zip,包括 CRLF

java - 设置以 Java 结尾的默认行

c - 从fgets()输入中删除结尾的换行符

mysql - shell脚本中的条件mysql操作

windows - 使用 PuTTY 作为本地终端仿真器?