Writing this Bash Script to accept Arguments?

0

How would I go about converting this bash script:

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

To accept a username and a password?

Urda

Posted 2010-04-07T15:39:29.350

Reputation: 843

1Please be aware that command line arguments can generally be seen by other users on the system. – coneslayer – 2010-04-07T15:45:44.093

True, but this is a closed environment where only an admin can get in, and all other users have been "jailed" away for SFTP purposes. – Urda – 2010-04-07T15:52:33.017

Answers

5

First, you should avoid that lots of sudo calls. Instead, you should run the script with sudo. The final version would look like this:

#!/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"

Quoting is necessary because the user name may contain spaces (but sure, it usually doesn't).

Edited to work.

petersohn

Posted 2010-04-07T15:39:29.350

Reputation: 2 554

Works great! Anyway to stop the script from running if no user is provided? – Urda – 2010-04-07T20:39:04.763

2if [ -z $1 ]; then echo "No username provided. Usage: $0 username"; exit 2; fi – Paused until further notice. – 2010-04-07T21:25:14.220

1echo "blah" >&2 to get extra points for proper stderr usage. – user1686 – 2010-04-08T12:10:12.533