I have an alias in my server's /etc/profile which generates a random directory on command, like this:

alias rdir="mkdir -p ./`cat /dev/random | tr -cd 'a-z0-9' | head -c 8`/"

But it turns out this generates always the same string (in this case: directory). I figured out already this seems to be related to source'ing the profile file and only generates a new random string after I call source /etc/profile.

Now, I wonder, how do I generate a random string in an alias which always changes when I call the alias, like in this example: rdir? (Without re-source-ing?)

  • 2
    You also want to use /dev/urandom instead of /dev/random. – cuonglm Jul 21 '15 at 8:17
  • 6
    Why not simply use mktemp --tmpdir=. -d XXXXXXXX ? It would even check against existing folders an make sure it is a new directory. – FelixJN Jul 21 '15 at 8:51

Use single quotes instead of double quotes:

alias rdir='mkdir -p ./$(cat /dev/urandom | tr -cd 'a-z0-9' | head -c 8)/'

Now, the statement is evaluated every time the alias is called. With double quotes the statement is evaluated, when defining the alias, therefore static.

Also a simpler solution to create a random directory inside the current working directory would be to use mktemp:

alias rdir='mktemp -d --tmpdir=./'

You can also use pwgen instead of cating and filtering /dev/random:

alias mkranddir='mkdir $(pwgen -s 8 1)'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.