编写此 Bash 脚本来接受参数?

编写此 Bash 脚本来接受参数?

我该如何转换这个 bash 脚本:

mkdir /store/sftp/%USERNAME%

sudo useradd -d /incoming %USERNAME%
sudo passwd %USERNAME%
## Password needs to be typed or passed in here
sudo usermod -g sftp %USERNAME%
sudo usermod -s /bin/false %USERNAME%

sudo chmod 755 /store/sftp/%USERNAME%
sudo chown root:root /store/sftp/%USERNAME%
sudo mkdir /store/sftp/%USERNAME%/incoming
sudo chown %USERNAME%:sftp /store/sftp/%USERNAME%/incoming

接受用户名和密码吗?

答案1

首先,你应该避免大量sudo调用。相反,你应该使用 来运行脚本sudo。最终版本将如下所示:

#!/bin/bash

# first check for root user
if [ ! $UID -eq 0 ]; then
    echo "This script must be run as root."
    exit 1
fi

# check if the user provided an argument
if [ -z $1 ]; then
    echo "No username provided. Usage: $0 username"
    exit 2
fi 

username=$1 # set the first argument as the username

mkdir "/store/sftp/$username"

useradd -d /incoming "$username"
passwd "$username"
## Password needs to be typed or passed in here
usermod -g sftp "$username"
usermod -s /bin/false "$username"

chmod 755 "/store/sftp/$username"
mkdir "/store/sftp/$username/incoming"
chown "$username:sftp" "/store/sftp/$username/incoming"

引用是必要的,因为用户名可能包含空格(但通常不包含)。

已编辑,可供使用。

相关内容