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

Bash脚本读取new_user.txt报错:文件不存在,请求修复指导

修复Bash脚本的文件找不到错误

错误根源

脚本中使用了$new_user.txt这个未定义的变量,Bash会将未定义变量解析为空字符串,导致实际执行的是done < .txt,因此触发"找不到文件"的错误。

修复后的脚本

直接使用实际文件名(无需变量包裹,除非你需要动态指定路径),同时处理原文件行首的多余空格,避免用户名带空格:

#!/bin/bash

while read -r line || [[ -n "$line" ]]; do
  # 去除行首空格,避免用户名包含无效空格
  trimmed_line=$(echo "$line" | sed 's/^[[:space:]]*//')
  username=$(echo "$trimmed_line" | cut -d: -f1)
  GECOS=$(echo "$trimmed_line" | cut -d: -f5)
  homedir=$(echo "$trimmed_line" | cut -d: -f6)
  echo "adduser -g '$GECOS' -d '$homedir' -s /bin/bash '$username'"
done < "new_user.txt"

可选优化(动态指定文件路径)

如果需要灵活切换目标文件,可以先定义变量并赋值:

#!/bin/bash
# 定义文件路径,可替换为绝对路径如"/home/you/new_user.txt"
USER_FILE="./new_user.txt"

while read -r line || [[ -n "$line" ]]; do
  trimmed_line=$(echo "$line" | sed 's/^[[:space:]]*//')
  username=$(echo "$trimmed_line" | cut -d: -f1)
  GECOS=$(echo "$trimmed_line" | cut -d: -f5)
  homedir=$(echo "$trimmed_line" | cut -d: -f6)
  echo "adduser -g '$GECOS' -d '$homedir' -s /bin/bash '$username'"
done < "$USER_FILE"

内容的提问来源于stack exchange,提问作者eggs

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 04:06:27