Bash脚本;与for循环混淆

时间:2014-04-22 22:40:27

标签: bash for-loop

我需要为目录中的每个项目创建一个for循环。

我的问题是for循环没有像我期望的那样发挥作用。

  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只是脚本选项的开关。

我遇到的问题是nitems计数根本没有减少,就好像for循环只进入一次。有什么我想念的吗?

由于

3 个答案:

答案 0 :(得分:3)

善良,不要依赖ls来迭代文件 local仅在函数中有用 使用文件名扩展模式将文件名存储在数组中。

  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

使用此技术可以安全地处理名称中包含空格,甚至是换行符的文件。

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

感谢所有建议。我发现问题是将$IFS更改为":"。虽然我的意思是为了避免文件名中的空格问题,但这只是复杂的事情。