Assign a variable with 10 character long random string using /dev/random in bash?

bash, cat, random, variables

Solution

The problem here is that you're trying to read an input stream with `cat /dev/random`, which by itself will never terminate (same thing as trying to do `cat /dev/stdin` for example). You can fix it by doing something like

#!/bin/bash
tmp_pass=0
if [ $tmp_pass = 0 ]; then
        tmp_pass=`head -c 10 /dev/random | base64`
        echo "${tmp_pass:0:10}" #cut to 10 characters after base64 conversion
fi

Problem

Trying to create a 10 character password and assign it to a variable and echo it back to the stdout. This is the script I've created so far, but it doesn't work. I know there are other ways to do this, but I've never been really good as using the `|` (pipe) to send information from 1 action to another when it involves more than 1 step. ``` #!/bin/bash tmp_pass=0 if [ $tmp_pass=0 ]; then tmp_pass=`cat /dev/random` tmp_pass=$(head tmp_pass -c 10 | base64) echo $tmp_pass fi ``` Ideally, what I want is an example like this: - Define the variable (eg - `tmp_pass`) - Set variable to `0` - If variable `eq 0` then give it a new assignment - Assign the variable the result of this: - Generate random string - Grab the first 20 bytes of the random string - Encode it as base64 - Cut it to the first 10 characters of the base64 Note: This was not shown in my original script up above, but it did see it once using `echo filename(1:10)` or something like that to limit it to echo the first 10 characters of line 1. I understand this could be done on 1 single line, but am unsure of how to write it out, any examples would be most appreciated.

Original source