': not a valid identifier for read

16,405

Solution 1

The text file that constitutes the shell script was written in Notepad++. This editor saves files as DOS text files by default which, from the Unix point of view, has a superfluous carriage return (\r) at the end of each line. This confuses sh.

To remove it:

$ tr -d '\r' <q.sh >q-new.sh
$ mv q-new.sh q.sh

The script does lack a #!-line (as pointed out in comments), but as long as you run it with an explicit interpreter (sh q.sh), this is not needed.

Adding the line

#!/bin/sh

would (after chmod +x q.sh) make running it as ./q.sh behave exactly the same as running it with sh q.sh.

Solution 2

Another way to convert the carriage return for Unix, if you have access to Notepad++. In Notepad, go on : Edit -> EOL conversion -> Unix (LF)

In French, it's : Edition -> Convertir les sauts de ligne -> Converti au format Unix (LF)

It can be faster.

Share:
16,405

Related videos on Youtube

Jan Nutcha
Author by

Jan Nutcha

Updated on September 18, 2022

Comments

  • Jan Nutcha
    Jan Nutcha over 1 year

    I use Notepad++ and type:

        read s
        echo "$s"
    

    The Output is:

    <code>': not a valid identifier</code>

    And then I try to put semicolon:

    read s;
    echo "$s"
    

    and the Output is:

    enter image description here

    I save the file as q.sh and run with cygwin but still I cannot use read operator so I'm getting confused. I have tried other editors like vi also but the output is the same.

    What is wrong? How to make it work?

    • John1024
      John1024 over 6 years
      Your file has windows-style line-endings. You need to remove them. See instructions here.
    • DavidPostill
      DavidPostill over 6 years
      You are also missing #!/bin/bash as the first line of the shell script.
    • Jan Nutcha
      Jan Nutcha over 6 years
      Oh Ok I got it thank you John1024 and DavidPastill