gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:56:19 27 4
gpt4 key购买 nike

考虑这个简单的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com