简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM