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
- Generate a random number in Bash between 1 to 20 or as per your need:
echo $((1 + $RANDOM % 20))
- Store the number into a shell variable:
random=$((1 + $RANDOM % 20))
- Build mkdir command:
mkdir -v "A${random}"
- Do you need a large random number? Say 1 to 500?
random=$((1 + $RANDOM % 500))
- How about more Random numbers? Just use $RANDOM:
echo $RANDOM
- So the command is:
mkdir -v "A${RANDOM}"
- 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:
And:
And:
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:
#!/bin/bash
random="$((1 + $RANDOM % 20))"
dir_name="A"
if [ ! -d "$dir_name" ]
then
echo "mkdir $dir_name"
else
dir_name="${dir_name}${random}"
echo "mkdir $dir_name"
fi
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)) )