Home > database >  Bash Script how to create a directory for a user which username consist of two words
Bash Script how to create a directory for a user which username consist of two words

Time:05-18

I have a bash script that asks for a username and a password. Based on the provided name and the password the script will create a user directory in /home for the user. Inside the directory a user file is also created.

Problem: If a user enters a username consisting of two words (like "Carl Eric") it creates two different directories named Carl and Eric. I want the script to create only one user directory with the name Carl OR Eric.

Here is my code:

#!/bin/bash
#create user script
clear
read -p "Provide username: " u_name
read -s -p "Provide password: " u_password
echo "Creating your working directory and file!!!!"
cd /home/
mkdir ${u_name}_d
cd ${u_name}_d
touch ${u_name}_f
exit 0

CodePudding user response:

Whenever you expect an input string to contain spaces and you want to treat it as a single string, try to enclose it in double-quotes.

mkdir "${u_name}_d"

CodePudding user response:

(like "Carl Eric") ... I want the script to create only one user directory with the name Carl OR Eric.

You can use a standard shell parameter expansion.

For example, ${u_name##*[[:space:]]} strips all the characters up to and including the last space character; when there is no space char in u_name, it is equivalent to $u_name.

In your case you're almost sure that there won't be any trailing space char because read (with the default IFS value) removes them.

Here's a fixed code:

#!/bin/bash
clear

read -p "Provide username: " u_name

IFS='' read -r -s -p "Provide password: " u_password

echo "Creating your working directory and file!!!!"

u_name=${u_name##*[[:space:]]}

mkdir -p "/home/${u_name}_d/" &&
touch "/home/${u_name}_d/${u_name}_f"

It's not ready for production though; there are several issues:

  • validate u_name:
      - not empty
      - not .
      - not ..
      - do not contain /
      - etc...
        remark: in fact it's easier to only allow a fixed set of valid characters
  • enforce a password policy
  • provide a way to re-input the data in case of erroneous input
  • Related