I want to create directories in bash by iterating over values from multiple loops (here for simplicity just 2) while skipping identical values. A demonstrating example looks like this:

for i in 1 2 3; do for j in 1 2 3; do mkdir $i$j; done, done

This gives me folders named 11, 12, 13, 21, 22, 23, 31, 32, 33, but I want to have only folders with different digits, so 11, 22 and 33 should not exist. Is there a convenient for loop option to skip identical values?

Alternatively one could also create all folders and delete those with multiple values afterwards, but this seems very inefficient if there are multiple loops with many entries.


Note: The loops below run from 1 to 9 using brace expansions. Use {1..3} or 1 2 3 to do exactly as in the question.

Compare $i and $j to make sure that they are different before creating the directory:

for i in {1..9}; do
    for j in {1..9}; do
        [ "$i" -ne "$j" ] && mkdir "$i$j"

The -ne test tests for arithmetic inequality. If you are looping over strings, use != instead. If the test is true ($i and $j are different), the directory is created with mkdir.

[ "$i" -ne "$j" ] && mkdir "$i$j" is a short-cut way of writing

if [ "$i" -ne "$j" ]; then
    mkdir "$i$j"

To delete all directories that have names like 11, 22 etc.:

for i in {1..9}; do
    rmdir "$i$i"

This assumes that the directories are empty. Use rm -rf "$i$i" if they are not empty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.