views:

40

answers:

1

Hi,

I'm using the following to generate a random password in a shell script:

DBPASS=</dev/urandom tr -dc A-Za-z0-9| (head -c $1 > /dev/null 2>&1 || head -c 8)

When i run this in a file on its own like this:

#!/bin/sh
DBPASS=</dev/urandom tr -dc A-Za-z0-9| (head -c $1 > /dev/null 2>&1 || head -c 8)
echo $DBPASS

A password is echoed. When i incorporate it into a larger script though the variable never seems to get created for some reason,

so for example this doesn't work (the oldpass string is replaced with nothing):

DBPASS=</dev/urandom tr -dc A-Za-z0-9| (head -c $1 > /dev/null 2>&1 || head -c 8)
sed -i s/oldpass/$DBPASS/ mysql_connect.php

If i manually set the variable though everything is fine. I must admit i'm not totally sure how the password is being generated. If it helps to clarify what the issue might be, this script is contained within a postwwwact cPanel script

can anyone see what the issue might be?

+1  A: 

When $1 evaluates to null (unset), the second head is run and it's what's outputting the string. The echo is not since $DBPASS is null. You need to use command substitution to get the output into the variable:

DBPASS=$(</dev/urandom tr -dc A-Za-z0-9| (head -c $1 > /dev/null 2>&1 || head -c 8))

Also, since the first head is redirected to /dev/null, nothing will be output if $1 is not null. What is it that you inted for that clause to do?

If what you're wanting is to provide a default length if one is not provided as an argument, then try this:

DBPASS=$(</dev/urandom tr -dc '[:alnum:]' | head -c ${1:-8} 2>&1)

I threw in the '[:alnum:]' for free.

Dennis Williamson
to be honest this is just a snippet i was given by another developer, can it be improved?
seengee
@snaken: see my edit.
Dennis Williamson
Thanks, fyi i basically want an 8 character random password, there will never be an argument passed to it.
seengee
seengee