JSarwer
JSarwer

Reputation: 313

Bash scripting; confused with for loop

I need to make a for loop that loops for every item in a directory.

My issue is the for loop is not acting as I would expect it to.

  cd $1

  local leader=$2
  if [[ $dOpt = 0 ]]
  then
        local items=$(ls)
        local nitems=$(ls |grep -c ^)
  else
        local items=$(ls -l | egrep '^d' | awk '{print $9}')
        local nitems=$(ls -l | egrep '^d' | grep -c ^)
  fi

  for item in $items;
  do
     printf "${CYAN}$nitems\n${NONE}"
     let nitems--
     if [[ $nitems -lt 0 ]]
     then
          exit 4
     fi
     printf "${YELLOW}$item\n${NONE}"
  done

dOpt is just a switch for a script option.

The issue I'm having is the nitems count doesn't decrease at all, it's as if the for loop is only going in once. Is there something I'm missing?

Thanks

Upvotes: 0

Views: 102

Answers (3)

glenn jackman
glenn jackman

Reputation: 246744

Goodness gracious, don't rely on ls to iterate over files.
local is only useful in functions.
Use filename expansion patterns to store the filenames in an array.

  cd "$1"
  leader=$2             # where do you use this?

  if [[ $dOpt = 0 ]]
  then
      items=( * )
  else
      items=( */ )       # the trailing slash limits the results to directories
  fi
  nitems=${#items[@]}

  for item in "${items[@]}"     # ensure the quotes are present here
  do
      printf "${CYAN}$((nitems--))\n${NONE}"
      printf "${YELLOW}$item\n${NONE}"
  done

Using this technique will safely handle files with spaces, even newlines, in the name.

Upvotes: 3

JSarwer
JSarwer

Reputation: 313

Thanks for all the suggestions. I found out the problem was changing $IFS to ":". While I meant for this to avoid problems with whitespaces in the filename, it just complicated things.

Upvotes: 0

user3520197
user3520197

Reputation:

Try this:

if [ "$dOpt" == "0" ]; then 
    list=(`ls`)
else
    list=(`ls -l | egrep '^d' | awk '{print $9}'`)
fi

for item in `echo $list`; do
    ... # do something with item
done

Upvotes: 0

Related Questions