aa:~/test$ ./monitor_system.sh
-bash: ./monitor_system.sh:/bin/bash^M:解释器错误: 没有那个文件或目录

这个错误是因为脚本文件包含Windows风格的换行符(CRLF,即\r\n),而Linux只需要LF(\n)。^M表示回车符(Carriage Return)。

解决方法

方法1:使用dos2unix转换

# 安装dos2unix(如果尚未安装)
sudo apt update
sudo apt install dos2unix

# 转换文件格式
dos2unix monitor_system.sh

# 然后重新执行
chmod +x monitor_system.sh
./monitor_system.sh

方法2:使用sed删除回车符

# 删除Windows回车符
sed -i 's/\r$//' monitor_system.sh

# 或者使用更明确的方式
sed -i 's/\x0D$//' monitor_system.sh

# 然后重新执行
chmod +x monitor_system.sh
./monitor_system.sh

方法3:使用tr命令

# 使用tr删除回车符
tr -d '\r' < monitor_system.sh > monitor_system_fixed.sh
mv monitor_system_fixed.sh monitor_system.sh

# 或者直接修改原文件
cat monitor_system.sh | tr -d '\r' > temp.sh && mv temp.sh monitor_system.sh

# 然后重新执行
chmod +x monitor_system.sh
./monitor_system.sh

方法4:使用vim修复

# 用vim打开文件
vim monitor_system.sh

# 在vim中执行以下命令
:set ff=unix
:wq

# 然后重新执行
chmod +x monitor_system.sh
./monitor_system.sh

方法5:临时使用bash执行(不修改文件)

# 直接使用bash解释器执行,避免权限问题
bash monitor_system.sh

验证修复结果

检查文件格式

# 查看文件格式
file monitor_system.sh

# 或者使用cat显示特殊字符
cat -A monitor_system.sh

# 使用hexdump查看十六进制
hexdump -C monitor_system.sh | head -5

正确的文件应该显示

  • file命令显示:monitor_system.sh: Bourne-Again shell script, ASCII text executable
  • cat -A不应该显示^M字符

预防措施

Git配置自动转换

如果文件来自Git仓库,配置Git自动处理换行符:

# 全局配置Git自动转换
git config --global core.autocrlf input

# 或者针对当前仓库
git config core.autocrlf input

# 对于Windows用户
git config --global core.autocrlf true

编辑器设置

在编辑器中设置使用Unix换行符:

  • VS Code: 右下角点击"CRLF"改为"LF"
  • Notepad++: 编辑 → 文档格式转换 → 转换为Unix格式
  • Sublime Text: View → Line Endings → Unix

完整修复示例

# 进入脚本目录
cd ~/test

# 检查当前文件格式
file monitor_system.sh
cat -A monitor_system.sh | head -3

# 修复文件格式(选择一种方法)
dos2unix monitor_system.sh

# 验证修复
file monitor_system.sh

# 添加执行权限并运行
chmod +x monitor_system.sh
./monitor_system.sh

如果上述方法都不行

检查shebang行

可能是shebang行本身有问题:

# 查看脚本第一行
head -1 monitor_system.sh

# 如果shebang行有问题,重新创建脚本
{
    echo '#!/bin/bash'
    tail -n +2 monitor_system.sh
} > monitor_system_fixed.sh

mv monitor_system_fixed.sh monitor_system.sh
chmod +x monitor_system.sh
./monitor_system.sh

重新创建脚本

如果文件损坏严重:

# 备份原文件
cp monitor_system.sh monitor_system.sh.backup

# 重新创建脚本内容
cat > monitor_system.sh << 'EOF'
#!/bin/bash
# 系统监控脚本
echo "=== 系统监控报告 ==="
echo "主机名: $(hostname)"
echo "运行时间: $(uptime)"
echo "内存使用:"
free -h
echo "磁盘使用:"
df -h
EOF

chmod +x monitor_system.sh
./monitor_system.sh

选择其中一种方法,应该能解决你的问题。推荐使用dos2unixsed方法,它们最简单有效。

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐