One line command to create directories with a name followed by random number

I want one-line command which creates directory called A in the current path
if A exists, then create a random number after it, for example
A05 , A15 , A20
each time we run the command, it should give another random

  1. Generate a random number in Bash between 1 to 20 or as per your need:
    echo $((1 + $RANDOM % 20))
  2. Store the number into a shell variable:
    random=$((1 + $RANDOM % 20))
  3. Build mkdir command:
    mkdir -v "A${random}"
  4. Do you need a large random number? Say 1 to 500?
    random=$((1 + $RANDOM % 500))
  5. How about more Random numbers? Just use $RANDOM:
    echo $RANDOM
  6. So the command is:
    mkdir -v "A${RANDOM}"
  7. Of course, you can print command before executing it in the current dir. For example:
    echo mkdir -v "A${RANDOM}"
    random=$((1 + $RANDOM % 20))
    echo mkdir -v "A${random}"

For more info see:



what about creating A for the first time if it doesn’t exist?
for the first time, the command checks whether A exists or not
if A exists, then start creating new directories that have name A01, A15, etc…
If A doesn’t exists, then create it.

That is easy, use the if…else…fi as follows:

random="$((1 + $RANDOM % 20))"

if [ ! -d "$dir_name" ]
    echo "mkdir $dir_name"
    echo "mkdir $dir_name"
1 Like

I would like it in one line command (one line command bash)

random="$((1 + $RANDOM % 20))" && dir_name="A" && { [ ! -d "$dir_name" ] && mkdir -v "$dir_name"  ||  dir_name="${dir_name}${random}"; [ ! -d "$dir_name" ] && mkdir -v "$dir_name"; }
1 Like

I have ended up with this
[ ! -d A ] && mkdir A || mkdir A$(echo $((RANDOM%20)) )