You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WSL2中使用While循环遭遇报错问题求助

Fixing Bash Loop Script Errors in WSL2

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:

  1. Use dos2unix (the easiest method)
    First, install the tool if you don't have it already:

    sudo apt update && sudo apt install dos2unix
    

    Then run it on your script to fix the line endings:

    dos2unix loop_learning.sh
    
  2. Use sed if you don't want to install anything
    Run this command to strip out the extra \r characters 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 nano or vim—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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:27:31