Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random filename in unix shell

I would like to generate a random filename in unix shell (say tcshell). The filename should consist of random 32 hex letters, e.g.:

c7fdfc8f409c548a10a0a89a791417c5 

(to which I will add whatever is neccesary). The point is being able to do it only in shell without resorting to a program.

like image 447
R S Avatar asked May 08 '10 11:05

R S


People also ask

How do you create a filename in Unix?

If you're using a window manager, you can usually press Ctrl + Alt + T to open a new terminal window. If not, log into the system on which you want to create a file through the console. Type cat > newfilename and press ↵ Enter . Replace newfilename with whatever you'd like to call your new file.

How do I create a temp file in bash?

A temp file can be created by directly running mktemp command. The file created can only be read and written by the file owner by default. To ensure the file is created successfully, there should be an OR operator to exit the script if the file fails to be created.

What is $@ in shell script?

$@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What is $@ in Linux?

"$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...). So basically, $# is a number of arguments given when your script was executed. $* is a string containing all arguments. For example, $1 is the first argument and so on.


1 Answers

Assuming you are on a linux, the following should work:

cat /dev/urandom | tr -cd 'a-f0-9' | head -c 32 

This is only pseudo-random if your system runs low on entropy, but is (on linux) guaranteed to terminate. If you require genuinely random data, cat /dev/random instead of /dev/urandom. This change will make your code block until enough entropy is available to produce truly random output, so it might slow down your code. For most uses, the output of /dev/urandom is sufficiently random.

If you on OS X or another BSD, you need to modify it to the following:

cat /dev/urandom | env LC_CTYPE=C tr -cd 'a-f0-9' | head -c 32 
like image 99
fmark Avatar answered Sep 23 '22 02:09

fmark