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

Bash脚本读取users.txt仅处理首行,后续用户未被遍历

问题原因

你的脚本只处理首行用户的核心原因是**ssh命令会默认占用标准输入(stdin)**,当在while read循环中执行ssh时,它会把users.txt中剩余的所有行当作自己的输入读取,导致read命令无法获取后续行,循环只执行一次。

虽然你已经添加了-n参数(告诉ssh不读取stdin),但在某些环境下可能效果不稳定,或者还有其他读取行的问题影响了循环执行。

解决方案

1. 修复后的完整脚本

修改读取行的方式并强制隔离ssh的输入,确保循环能遍历每一行:

#!/bin/bash

input_file="users.txt"
found_file="users_found.txt"
not_found_file="users_not_found.txt"

# 清空输出文件(更简洁高效的写法)
> "$found_file"
> "$not_found_file"

# 使用IFS= read -r确保读取完整行,保留空格和特殊字符
while IFS= read -r user; do
    # 将ssh的输入重定向到/dev/null,彻底避免占用循环的stdin
    if ssh ldaptest /opt/ldap/ldapsearch --user "$user" >/dev/null 2>&1 < /dev/null; then
        echo "$user" >> "$found_file"
    else
        echo "$user" >> "$not_found_file"
    fi
done < "$input_file"

2. 关键优化点说明

  • IFS= read -r user:IFS=保证读取行时不忽略行首行尾的空格,-r禁止read转义反斜杠字符,确保完整读取每一行内容。
  • 给变量加双引号:如"$user"、"$found_file",避免用户名称包含空格或特殊字符时出现命令解析错误。
  • ssh ... < /dev/null:强制将ssh的输入重定向到空设备,彻底隔离循环的标准输入,解决ssh抢读剩余行的问题。

3. 可选:清理用户文件格式

如果你的用户名称不需要保留首尾空格,可以先清理文件中的多余空白字符:

sed -i 's/^[[:space:]]*//;s/[[:space:]]*$//' users.txt

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:52:55