0

I have this code:

# GENERATE RANDOM PASSWORD
#  $1 = number of characters; defaults to 32
#  $2 = include special characters; 1 = yes, 0 = no; defaults to 1
function randpass() {
  [ "$2" == "0" ] && CHAR="[:alnum:]" || CHAR="[:graph:]"
    cat /dev/urandom | tr -cd "$CHAR" | head -c ${1:-32}
    echo
}

randpass
randpass 10
randpass 20 0

SSHKEYPASS = randpass 10

I want to be able to generate a random password and store it as a variable. However, although randpass works just fine, when I try and set ```SSHKEYPASS`` to the result of randpass it doesn't work. So, how can I use my randpass function to generate a random password on the SSHKEYPASS variable.

Thank you.

J.Zil
  • 2,397
  • 7
  • 44
  • 78

1 Answers1

1

The problem is the last line SSHKEYPASS=randpass 10 what this does is that it assigns the return status of the randpass function and not the output of the randpass function , inorder to assign the output of randpass function you have to use process substitution as below

SSHKEYPASS=$(randpass 10)

the above command will populate the SSHKEYPASS with the standard output of randpass function

Ram
  • 1,115
  • 8
  • 20
  • Actually, what the erroneous command does is to assign the static string value `randpass` to the variable for the duration of the execution of the command `10`, which should be `command not found` in all but the most unusual circumstances. – tripleee Sep 18 '14 at 14:32
  • This is a very common question; you would spend your time more wisely by finding a similar question with good answers, and mark this as a duplicate. (Admittedly, less reputation gains potential for you in the bargain.) – tripleee Sep 18 '14 at 14:34