在Bash中循环使用空格的目录

jak*_*kev 14 bash

在bash脚本中,我想迭代当前工作目录中的所有目录并对它们执行操作.它们可能包含特殊符号,尤其是空格.我怎样才能做到这一点?我有:

for dir in $( ls -l ./)
do
    if [ -d ./"$dir" ]
Run Code Online (Sandbox Code Playgroud)

但是这会以他们名字中的空格跳过我的目录.任何帮助表示赞赏.

Pau*_*ce. 37

尝试一下:

for dir in */
Run Code Online (Sandbox Code Playgroud)

  • 哇,这确实有效,甚至在有空格的目录上也是如此.那么,bash必须在扩展通配符时隐式引用这些值?我喜欢它. (2认同)
  • @Air:`shopt -s globstar; 对于Bash 4中**/`中的dir将会递归. (2认同)

Spl*_*iFF 11

选择解决方案:

http://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html

一般的想法是更改默认分隔符(IFS).

#!/bin/bash
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for f in *
do
  echo "$f"
done
IFS=$SAVEIFS
Run Code Online (Sandbox Code Playgroud)