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

Time:12-14

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

CodePudding user response:

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 *.

  • Related