Shell script works in console, but not when saved as text file
Consider this simple shell script:
#!/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
When I paste it into the cygwin window it works fine, but when I save it as a test.sh text file and run it from the cygwin terminal I get this:
$ ./test.sh
./test.sh: line 4: syntax error near unexpected token `$'do\r''
'/test.sh: line 4: `do
However, if I remove the newlines, it works:
#!/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
How can I make the script more readable by maintaining newlines in the file \n
doesn't seem to work.
source to share
Your characters \r
come from a windows file where newlines are defined with \r\n
. In UNIX, a newline is only defined with help \n
, so it \r
remains an orphan and causes these problems.
What you can do is convert the file to UNIX mode using the command dos2unix
.
Additional information: Does the Windows carriage return \ r \ n from two characters or one character? :
The two characters together represent a newline on Windows. Whereas Linux,
\n
introduces a newline. It moves the cursor to the start of a new line on Linux. On Windows, the cursor will remain in the same column in the console, but on the next line.
\r
- carriage return;\n
- line.
source to share