I’m trying make simple function for the useradd command and to quickly improve my poor shell programming skills.
useradd -m -g [initial_group] -G [additional_groups] -s [login_shell] [username]
Right now I’m somewhat unsure how to function with optional arguments. After some Googling and I think might have a handle on that, just need to play around the code.
One thing that I’m unsure about is the logic and I’m curious on how you guys would go about writing this. I’m sure it will be better then what I could hack together.
Here is how I going to try setup my function arguments, for the login shell and the initial group I would them to have generic defaults.
arg1 - userName, required
arg2 - loginShell, optional (default: /bin/bash)
arg3 - initGroup, optional (default: users)
arg4 - otherGroups, optional (default: none)
This is some lame pseudo code on how I’m thinking to structure this.
function addUser( userName, loginShell, initGroup, otherGroups){
// Not how I would go about this but you should get the point
string bashCmd = "useradd -m -g ";
// Adding the initial user group
if(initGroup == null){
bashCmd += "users";
} else {
bashCmd += initGrop;
}
// Adding any additional groups
if(otherGropus != null){
bashCmd += " -G " + otherGroups;
}
if(loginShell == null){
bashCmd += " -s /bin/bash " + userName;
} else {
bashCmd += " -s " + loginShell + " " + userName;
}
}
These are the links I’m going by
http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-8.html
Passing parameters to a Bash function
How to write a bash script that takes optional input arguments?
@rob mayoff’s answer is the simplest way to accomplish this, but I thought I’d take a stab at turning your pseudo code into real shell syntax to point out some standard gotchas for people used to “real” programming languages. Three general notes first:
#!/bin/bashor run it with thebashcommand) if you need any bash extensions. If you are only using basic Bourne shell features and syntax, run it with sh (#!/bin/shor theshcommand) instead. If you don’t know, assume you need bash.if [ -n "$2" ]; then, the space after the semicolon is optional (and there could also be a space before the semicolon), but all of the other spaces are required (without them the command will do something completely different). Also, in an assignment, there cannot be spaces around the equal sign, or (again) it’ll do something completely different.With that in mind, here’s my take on the function: