WSL2中使用While循环遭遇报错问题求助
Hey there! I totally get how frustrating it is when you copy a working example and it still throws errors—let's get this sorted out.
What's Causing the Errors?
The first error $'\r': command not found and the syntax error with done are both caused by Windows-style line endings (CRLF) in your script. Windows uses \r\n to end lines, but Bash (and all Linux-based shells) expect just \n. When you copied the code over, those extra \r characters got stuck in the script, and Bash tries to run them as commands—hence the weird, confusing errors.
How to Fix It
Here are two straightforward ways to convert your script to use Linux-style line endings:
Use
dos2unix(the easiest method)
First, install the tool if you don't have it already:sudo apt update && sudo apt install dos2unixThen run it on your script to fix the line endings:
dos2unix loop_learning.shUse
sedif you don't want to install anything
Run this command to strip out the extra\rcharacters manually:sed -i 's/\r$//' loop_learning.sh
Prevent This From Happening Again
- When writing or editing Bash scripts for WSL, use a text editor that lets you set line endings to LF (Linux-style). For example, in VS Code, check the bottom-right corner—you can click the current setting (like "CRLF") and switch to "LF".
- Or, just create and edit your scripts directly in the WSL terminal using tools like
nanoorvim—this way, you'll never accidentally introduce Windows line endings in the first place.
Once you fix the line endings, run your script again with ./loop_learning.sh and it should work perfectly: counting from 1 to 10, then printing "All done" at the end!
内容的提问来源于stack exchange,提问作者Santi

