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.

+3


source to share


3 answers


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.
+5


source


Without answering the question.

Operator

A case

is fine. Like the actual array.



fruitlist=( Apple Pear Tomato Peach Grape )
for fruit in "${fruitlist[@]}"; do
    case $fruit in
        Tomato|Peach) echo "I like ${fruit}es" ;;
        *) echo "I like ${fruit}s" ;;
    esac
done

      

+1


source


I always add the following header to my shell scripts to make cygwin ignore CR:

#!/bin/sh
if [ "$OSTYPE" = "cygwin" ]; then shopt -s igncr 2>/dev/null; fi # New version of Cygwin complains itself of CR

      

Note that the comment at the end of the second line is required.

0


source







All Articles