SHELL SCRIPT LINUX 使用用户输入设置密码

SHELL SCRIPT LINUX set password using user input

我想将新帐户的密码设置为用户输入的输入(字符串)。这似乎不起作用。顺便说一句,这是一个更大的脚本的一部分,我只包括了与这个问题相关的部分。

所以如果我 运行 代码我得到以下错误代码:/create-user.sh: line 36: user3:hej: command not found.The line here is不同,因为它是更大脚本的一部分。上面的“hej”是我输入 运行 代码时输入的密码。我猜 shell 认为“hej”应该是一个命令,但它应该是一个密码字符串。澄清一下,hej 应该是密码。

#!/bin/bash

# Get the username (login).
read -p "Please enter a username: "  username

# Get the password.
read -p "Please enter an initial password: " password

# Create the account.
useradd "$username"

# Set the password.
chpasswd | "$username":"$password"

$username:$password 应该是 chpasswd 命令的输入。您正在将 chpasswd 的输出传输到由此形成的命令。由于 username:password 不是命令的名称,因此会出现错误。

你想要的是:

chpasswd <<< "$username:$password"