CRLF line terminators cause the shell script to report an error: command not found

Line endings differ for Linux and Windows text files. In Linux, text files use "/n" for carriage return and line feed, while Windows uses "/r/n" for carriage return and line feed. Sometimes you need to pay attention to this when writing shell scripts on Windows, otherwise the shell script will report errors such as "No such file or directory" or "command not found line x". If you don't know the cause and effect, you will be quite depressed by this toss. . test.sh as shown below

[root@DB-Server myscript]# more test.sh 
. /home/oracle/.bash_profile
echo ' '
date
echo ' '

sqlplus test/test @/home/oracle/scripts/test.sql

echo ' '
date
echo ' '

During the execution of the test.sh script, "No such file or directory /home/oracle/.bash_profile" and "command not found line xx" are reported. If you check from the shell script syntax, there is no problem at all. It must be quite frustrating for not knowing the specific reason.

[oracle@DB-Server myscript]$ ./test.sh

: No such file or directory /home/oracle/.bash_profile

: command not found line 2: 

: command not found line 4: date

: command not found line 6: 

: command not found line 7:

If you look at test.sh with the file command, you will find that the file is encoded as ASCII, with CRLF line terminators. We can see ^M with cat -v test.sh (the hexadecimal of \r is 0D, and the corresponding control character is ^M). cat -v can see non-printing characters in the file.

[root@DB-Server myscript]# 
[root@DB-Server myscript]# file test.sh 
test.sh: ASCII text, with CRLF line terminators
[root@DB-Server myscript]# cat -v test.sh 
. /home/oracle/.bash_profile^M
echo ' '^M
date^M
echo ' '^M
^M
sqlplus test/test @/home/oracle/scripts/test.sql^M
^M
echo ' '^M
date^M
echo ' '^M
[root@DB-Server myscript]# 

We can use the file command to compare the format and encoding of a normal shell script. As follows

[oracle@DB-Server myscript]$ file myshell.sh

myshell.sh: Bourne-Again shell script text executable

There are many ways to solve this problem, such as directly using the vi editor to write shell scripts; using the cat command to create shell scripts, and then copying the scripts from the Windows text tool; the most convenient way is to use dos2unix to convert DOS format text files to Unix format or Linux format.

# unix format
 etc/hadoop/container-executor.cfg: ASCII text

# dos format
 etc/hadoop/container-executor.cfg: ASCII text, with CRLF line terminators  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324648708&siteId=291194637