0

I am trying to generate a random string of a certain length in Bash. This works in every other Bash shell I could test (Ubuntu 18.04 LTS and Debian 10)

$ cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 10 | head -n 1
n8a4wxvb01
$

cat /dev/urandom – endless stream of bytes

tr -dc ‘a-z0-9’ – only return lowercase characters and digits

fold -w 10 – break at 10 characters

head -n 1 – return the first line of the stream

In the Azure Cloud Shell Bash, this hangs. It returns the random string but never exits. The call to head -n 1 never exits after printing the value.

I have a work around but it seems backwards

head -n 10 /dev/urandom | tr -dc 'a-z0-9' | fold -w 10 | head -n 1
James P
  • 71
  • 4
  • What do you mean on "The call to head -n 1 never exits after printing the value."? – Charles Xu Jun 03 '20 at 01:28
  • If you run that command on Ubuntu 18.04 LTS, you get a single value value and the command completes. If you try this in Azure Cloud Shell Bash, you will see the command return a value but then hang. You can get it only exits with ctrl-c. I made this example easy enough so that anyone can cut and paste this and try it. – James P Jun 04 '20 at 11:32
  • If there is any doubt that it is the call to `head -n 1`, just remove it from the end of the statement and you will see an endless stream of 10 character random values – James P Jun 04 '20 at 11:44

2 Answers2

0

The command works fine both in personal Linux OS and the Azure Cloud Shell Bash.

Azure Cloud Shell Bash:

enter image description here

Personal Linux OS:

enter image description here

I don't think there would be a difference between them. The Azure Cloud Shell is just a VM running on Ubuntu 16.04 LTS. Take a look at the features of the Azure Cloud Shell.

Update:

You can take a look at the issue, the answers probably show the reasons that the command does not work in Azure Cloud Shell. And as I know it is not a high performing system. Otherwise, use cat is not a good idea to get a random string. I suggest the head.

Charles Xu
  • 29,862
  • 2
  • 22
  • 39
  • Yes. my work around works fine, but my original code does not. The first code snippet is idiomatically correct Bash and should work everywhere. `cat /dev/urandom | tr -dc 'a-z0-9' | fold -w 10 | head -n 1` does not work – James P Jun 05 '20 at 13:56
  • @JamesP See the updates, I think it's the possible reason. – Charles Xu Jun 08 '20 at 01:51
  • @JamesP Any more questions? Does it solve your problem? – Charles Xu Jun 11 '20 at 06:30
0

I prefer using openssl for creating random strings (as hex or base64):

openssl rand -hex 10

openssl rand -base64 10

https://www.openssl.org/docs/man1.0.2/man1/openssl-rand.html

Baked Inhalf
  • 3,375
  • 1
  • 31
  • 45