Generate a random filename in unix shell

前端 未结 14 627
说谎
说谎 2020-12-22 23:39

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

c7fdfc8f409c548a10a0a89a7         


        
相关标签:
14条回答
  • 2020-12-22 23:56

    Another thing you can add is running the date command as follows:

    date +%S%N
    

    Reads nonosecond time and the result adds a lot of randomness.

    0 讨论(0)
  • 2020-12-22 23:59

    Tested in zsh, should work with any BASH compatible shell!

    #!/bin/zsh
    
    SUM=`md5sum <<EOF
    $RANDOM
    EOF`
    
    FN=`echo $SUM | awk '// { print $1 }'`
    
    echo "Your new filename: $FN"
    

    Example:

    $ zsh ranhash.sh
    Your new filename: 2485938240bf200c26bb356bbbb0fa32
    $ zsh ranhash.sh
    Your new filename: ad25cb21bea35eba879bf3fc12581cc9
    
    0 讨论(0)
  • 2020-12-23 00:00

    Grab 16 bytes from /dev/random, convert them to hex, take the first line, remove the address, remove the spaces.

    head /dev/random -c16 | od -tx1 -w16 | head -n1 | cut -d' ' -f2- | tr -d ' '
    

    Assuming that "without resorting to a program" means "using only programs that are readily available", of course.

    0 讨论(0)
  • 2020-12-23 00:02

    Hope to add a (maybe) better solution to this topic.

    Notice: this only works with bash4 and some implement of mktemp(for example, the GNU one)

    Try this

    fn=$(mktemp -u -t 'XXXXXX')
    echo ${fn/\/tmp\//}
    

    This one is twice as faster as head /dev/urandom | tr -cd 'a-f0-9' | head -c 32, and eight times as faster as cat /dev/urandom | tr -cd 'a-f0-9' | head -c 32.

    Benchmark:

    With mktemp:

    #!/bin/bash
    # a.sh
    for (( i = 0; i < 1000; i++ ))
    do
        fn=$(mktemp -u -t 'XXXXXX')
        echo ${fn/\/tmp\//} > /dev/null
    done
    
    time ./a.sh 
    ./a.sh  0.36s user 1.97s system 99% cpu 2.333 total
    

    And the other:

    #!/bin/bash
    # b.sh
    for (( i = 0; i < 1000; i++ ))
    do
        cat /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 32 > /dev/null
    done
    
    time ./b.sh 
    ./b.sh  0.52s user 20.61s system 113% cpu 18.653 total
    
    0 讨论(0)
  • 2020-12-23 00:04

    If you are on Linux, then Python will come pre-installed. So you can go for something similar to the below:

    python -c "import uuid; print str(uuid.uuid1())"
    

    If you don't like the dashes, then use replace function as shown below

    python -c "import uuid; print str(uuid.uuid1()).replace('-','')"
    
    0 讨论(0)
  • 2020-12-23 00:05

    The first answer is good but why fork cat if not required.

    tr -dc 'a-f0-9' < /dev/urandom | head -c32
    
    0 讨论(0)
提交回复
热议问题