0

I want to create one bash script that takes as argument a directory from the command line and prints all my subdirectories. My script prints all the files that this directory has and does not enter in the if loop. What am I doing wrong and how to fix it?

#!/bin/bash
echo to argv[1] = $1
if [ -e $1 ] #exist the file
then if [ -d $1 ] # is directory
    then if [ -r $1 ] #we can read
        then for k in $(ls $1) #all the files in the arv[1] 
        do
            echo $k #print all the files of directory
            if [ -d $k ]
                then echo $k
            fi
        done
    fi
  fi
fi

1 Answer 1

3

[ -d $k ] tests whether $k is a directory relative to the current working directory, but you need to use

[ -d "$1/$k" ]

instead.

Also, instead of iterating over the output of ls, use

for k in $1/*

which makes the above change needless.

BTW, while, until, and for start a loop, but if doesn't. I'd call it an "if block".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.