Shell Directory – Creating Numerous Directories Using mkdir

directoryshell

I would like to create many directories using mkdir. Each directory name will consist of a prefix (a string) and an index (an integer). Suppose that I would like the prefix to be "s" and the indices to range from 1 to 50. This means that I would like to create directories titled:

s1, s2, … , s49, s50

Is there a way to do this automatically using mkdir? Thanks for your time.

Best Answer

You can do this with a shell script.

Pure sh - this will work even on pre-POSIX bourne shells:

n=1;
max=50;
while [ "$n" -le "$max" ]; do
  mkdir "s$n"
  n=`expr "$n" + 1`;
done

If you want to create a high number of directories, you can make the script faster by reducing it to a single call of mkdir as well as using shell builtins for testing and arithmetics. Like this:

n=1
max=50
set -- # this sets $@ [the argv array] to an empty list.

while [ "$n" -le "$max" ]; do
    set -- "$@" "s$n" # this adds s$n to the end of $@
    n=$(( $n + 1 ));
done 

mkdir "$@"

Zsh, ksh93 or bash make this much easier, but I should point out this is not built into mkdir and may not work in other shells. For larger cases, it may also be affected by limits on the number or total size of arguments that may be passed to a command.

mkdir s{1..50}
Related Question