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

问题描述

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

因此,如果我运行代码,我会得到以下错误代码:/create-user.sh: line 36: user3:hej: command not found。这里的行不同,因为它是更大脚本的一部分。上面的“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"