Search code examples
shellcreate-directory

Simple shell script that creates a dir with a random name


I'm trying to write a simple shell script in linux that creates directories with random names.

The names must be made from the date of the day followed by a random string like in this example: 2018-02-22y2Fdv9zzLVLupkl9El0dWalJAGTROLxE

This is the shell script

#!/bin/bash
# the date
DATAOGGI= echo -n $(date +"%Y-%m-%d")
# random string
RANDOM_STRING=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)
# the dir
NEW_DIR=$(echo -n ${DATAOGGI}${RANDOM_STRING})
echo $NEW_DIR
mkdir $NEW_DIR

Unfortunately, even if the variable NEW_DIR is correct echo $NEW_DIR -> 2018-02-22y2Fdv9zzLVLupkl9El0dWalJAGTROLxE

the name of the directory is y2Fdv9zzLVLupkl9El0dWalJAGTROLxE


Solution

  • try just:

    #!/bin/bash
    DATAOGGI=$(date +"%Y-%m-%d")
    RANDOM_STRING=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)
    mkdir "${DATAOGGI}${RANDOM_STRING}"
    

    apart from fact that it is not necessary in this example echo -n AFAIK has very inconsistent behavior and it is advised to use printf instead