简体   繁体   中英

Loop over directories with whitespace in Bash

In a bash script, I want to iterate over all the directories in the present working directory and do stuff to them. They may contain special symbols, especially whitespace. How can I do that? I have:

for dir in $( ls -l ./)
do
    if [ -d ./"$dir" ]

but this skips my directories with whitespace in their name. Any help is appreciated.

试试看:

for dir in */

Take your pick of solutions:

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

The general idea is to change the default seperator (IFS).

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

There are multiple ways. Here is something that is very fast:

find /your/dir -type d -print0 | xargs -0 echo

This will scan /your/dir recursively for directories and will pass all paths to the command "echo" (exchange to your need). It may call echo multiple time, but it will try to pass as many directory names as the console allows at once. This is extremely fast because few processes need to be started. But it works only on programs that can take an arbitrary amount of values as options. -print0 tells find to seperate file paths using a zero byte (and -0 tells xargs to read arguments seperated by zero byte) If you don't have the later one, you can do this:

find /your/dir -type d -print0 | xargs -0 -n 1 echo

or

find /your/dir -type d -print0 --exec echo '{}' ';'

The option -n 1 will tell xargs not to pass more arguments than one at the same time to your program. If you don't want find to scan recursively you can specify the depth option to disable recursion (don't know the syntax by heart though).

Though if that's usable in your particular script is another question ;-).

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