Random password variable disappears

I am 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 on a file myself:

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

      

Password is repeated. When I include it in a larger script, even though the variable is never created for some reason,

so for example this doesn't work (the oldpass line 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 have to admit, I'm not entirely sure how the password is generated. If it helps figure out what might be the problem, this script is contained in the postwwact cPanel script

can anyone understand what the problem is?

+2


a source to share


1 answer


When $1

evaluates to null (unset), the second runs head

and it outputs the string. echo

no, because $DBPASS

it is null. You need to use command substitution to get the result in a variable:

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

      

Also, since the first one is head

redirected to /dev/null

, nothing will be output if $1

not null. What did you do for this proposal?



If you want to provide a default length when not supplied as an argument, try this:

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

      

I chose '[:alnum:]'

for free.

+1


a source







All Articles