I have a script that I have copied and edited. There are a couple of lines in there that I need explaining if possible please.
These are the lines:
read -p "please enter the username you wish to create: " username
if id -u $username >/dev/null 2>&1; then
What does read -p do? What does id -u do? What does >/dev/null 2&1; do?
Then further on in the script, it has this line that says this:
sudo useradd -g $group -s $bash -d $homedir -m $username -p $password
Again please could someone explain all the minus signs in this line please? (-g, -s, -d, -m, -p)
First off, the structure <command> -<option> means that you want to execute <command> using the option corresponding to <option>. A - after a command means that the following letter is an option. Most commands have several options you can use. Options are usually defined using either a single letter or a couple of words separated by -.
Side Note: For options that are a couple of words rather than a single letter, often it will use two minus signs -- instead of one, signifying that it is a "long named" option.
So, using the read -p example, this means you want to execute read using the p option, which stands for prompt.
Now, sometimes an option will require an argument. In your examples, the options to useradd have arguments. Arguments are usually defined like <command> -<option> [argument]. So, in the useradd example, $group is an argument for the option g.
Now for the commands themselves:
read is a bash built-in (not a POSIX shell command) that reads from standard input.
-p option makes it read as a prompt, meaning it doesn't add a trailing newline before trying to read input.if checks the return status of the test command (in this case id -u $username >/dev/null 2>&1)
then part is executedid prints user groups and ids
-u option "prints only the effective user ID".>/dev/null 2>&1 redirects standard input and standard error to /dev/null, meaning they do not get printed to the terminal.useradd creates a new user
-g sets the initial group for the user-s sets the name of the user's login shell-d sets the name of the user's login directory-m says to create the user's home directory if it does not exist.-p defines the user's encrypted password.For future reference, you can look up commands in the linux manual pages by doing man <command> on the command line. These manual pages tell you what a command does, as well as explaining all of its options.
Bash built-ins like read are all on a single man page that is not the easiest thing to use. For those I find googling them easier. Usually http://ss64.com/ will come up in the results, which contains the info from the bash built-ins man page, but separated into different pages by command. I find this much easier to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With