Loop over directories with whitespace in Bash

后端 未结 3 412
予麋鹿
予麋鹿 2020-12-05 15:13

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.

相关标签:
3条回答
  • 2020-12-05 15:22

    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 ;-).

    0 讨论(0)
  • 2020-12-05 15:25

    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
    
    0 讨论(0)
  • 2020-12-05 15:32

    Give this a try:

    for dir in */
    
    0 讨论(0)
提交回复
热议问题