Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to quote the command substitution in a for loop with a variable inside of it?

Right now, my bash script isn’t doing what I want it to. I run "bash -x script" on my bash script to debug it and its testing all of the directories and files in my current directory not a different directory specified by the user. Just tell me how I’m quoting the command substitution wrong thats where the problem is at. It’s not looking at $dir variable when i run it.

Here’s my script:

  dir=$1
  
  for i in "$(ls $dir)"
  do
          if [ -d "$i" ]
          then
                     echo "$i"
          fi
  done

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Something like

dir=$1

for f in "$dir"/* ; do
    test -d "$f" || continue
    echo "$f"
done

The important thing here is to not loop over $(ls ...) since it fails on special characters, but rather use a pattern in which $dir is protected with "" but not the wildcard *.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading