从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
forloop syntax is messed up—doneeds to be properly placed after theforstatement, and you can't put variable assignments betweenforanddo. Also, the shebang line#!/bin/shneeds to be on its own line, not glued to theforcommand. - 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
passwdtarget: You're passing$passwordtopasswd, which would try to change the password for a user namedunixlab—not the user you're creating ($i). - Incomplete password input: The
passwdcommand 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 incat unix_tuesday.txt`` can break if usernames have spaces or special characters. Awhile readloop 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 -rto safely read each username from the file (the-rprevents 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
passwdcommand to target the correct user ($username) - Updated the
echo -eline to send the password twice, which satisfiespasswd's confirmation requirement
内容的提问来源于stack exchange,提问作者user3078335
相关产品推荐
相关产品推荐

