سؤال

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:

  1. Define the variable (eg - tmp_pass)
  2. Set variable to 0
  3. If variable eq 0 then give it a new assignment
  4. Assign the variable the result of this:
    1. Generate random string
    2. Grab the first 20 bytes of the random string
    3. Encode it as base64
    4. 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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

Add whatever special characters you would like to have in the password and stay away from /dev/random, it will run out of data and look like it is hanging.

tr -dc 'a-zA-Z0-9' < /dev/urandom | head -c10
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top