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

从Bash脚本创建用户账户:现有脚本无法正常运行求助

Fixing Your User Creation Shell Script

Hey there! Let's walk through what's broken in your script and get it working properly. I'll break down the issues and show you a corrected version.

The Main Issues in Your Original Code

Here's why your script isn't running:

  • Broken loop structure: Your for loop syntax is messed up—do needs to be properly placed after the for statement, and you can't put variable assignments between for and do. Also, the shebang line #!/bin/sh needs to be on its own line, not glued to the for command.
  • Invalid variable assignment: In shell scripting, you can't have spaces around the = sign. password = "unixlab" will be interpreted as a non-existent command instead of setting a variable.
  • Wrong passwd target: You're passing $password to passwd, which would try to change the password for a user named unixlab—not the user you're creating ($i).
  • Incomplete password input: The passwd command requires you to enter the password twice for confirmation. Your original code only sends it once, which will fail.
  • Unsafe file reading: Using for i in cat unix_tuesday.txt`` can break if usernames have spaces or special characters. A while read loop is more reliable.

Corrected Script

#!/bin/sh

# Set the password once, outside the loop
password="unixlab"

# Safely read each line from the file as a username
while read -r username; do
    # Skip empty lines to avoid errors
    [ -z "$username" ] && continue
    
    echo "Creating user account: $username"
    # Create the user (adduser may require additional flags depending on your distro)
    adduser "$username"
    # Send both password entries to passwd to confirm
    echo -e "$password\n$password" | passwd "$username"
done < unix_tuesday.txt

Key Fixes Explained

  • Moved the password assignment outside the loop so we don't re-set it every iteration
  • Used while read -r to safely read each username from the file (the -r prevents unexpected behavior with backslashes in usernames)
  • Added a check to skip empty lines in the input file
  • Wrapped variables in double quotes to handle usernames with spaces (though usernames usually don't have spaces, it's good practice)
  • Fixed the passwd command to target the correct user ($username)
  • Updated the echo -e line to send the password twice, which satisfies passwd's confirmation requirement

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:02:01