Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

bash - Why would a correct shell script give a wrapped/truncated/corrupted error message?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

TL;DR: Your script or data has Windows style CRLF line endings.

Convert to Unix style by deleting the carriage returns.


How do I check if my script or data has carriage returns?

They're detectable as ^M in the output of cat -v yourscript:

$ cat -v myscript
ls -l myfile^M

If your script doesn't have them, your data might -- especially if reading from ini/csv files or curl:

hostname=$(curl https://example.com/loginhost.txt)
ssh "$hostname"            # Shows strange error
echo "$hostname" | cat -v  # Shows myhost^M

How do I remove them?

Set your editor to save the file with Unix line endings, aka "line terminators" or "end-of-line characters", and resave it.

You can also remove them from a command line with dos2unix yourscript or cat yourscript | tr -d ' ' > fixedscript.

If found in your data, you can pipe your source through tr -d ' ':

hostname=$(curl https://example.com/loginhost.txt | tr -d '
')

Why do carriage returns cause strange error messages?

The "carriage return" character, aka CR or , causes the cursor to move to the start of the line, and continue printing from there. In other words, it starts overwriting the line from the start. This is why they wrap strangely:

Intended:     ssh: Could not resolve hostname myhost
: Name or service not known

Written:      ssh: Could not resolve hostname myhost

Overwritten:  : Name or service not known
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^                  
Result:       : Name or service not knownname myhost

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...