[prog] user bash script

John Clarke johnc+linuxchix at kirriwa.net
Fri Aug 12 18:53:36 EST 2005


On Fri, Aug 12, 2005 at 08:23:14 +0100, Noir wrote:

> I am writing a bash script to adduser which will first
> check if the u_name exist in /etc/passwd file. My
> code:
> 
> uname="`echo $uname | tr "[A-Z]" "[a-z]"`"

There's nothing wrong with this, but I'd suggest using grep's
case-insensitive matching instead to save this step.

> avail="`cat /etc/passwd | grep ^$uname:`"

Rather than cat the file and pipe it to grep, give grep the filename and
have it read it directly.

Do both of these and you reduce three shell commands (tr, cat, grep) and
two pipes to a single shell command (grep).  I'm not counting `echo'
because it's a bash built-in.

> if [ -e "$avail" ]; then

This won't work because `-e' tests that a file exists, not that the
string is not empty.  `-n' is what you should be using.

Here's how I'd do it:

    if test -n "`grep -i ^$uname: /etc/passwd`"
    then
        echo "User $uname already exists"
        exit 1
    fi

but only if I was the only one who could use it.  Otherwise I'd make
sure to sanitise $uname first to strip out shell meta-characters and
anything else that shouldn't appear in a username.


Cheers,

John
-- 
With a Dremel tool and a cut-off wheel, _everything_ takes a flat-blade
screwdriver.
            -- Matt Roberds


More information about the Programming mailing list