BASH Shell: For Loop File Names With Spaces

BASH for loop works nicely under UNIX / Linux / Windows and OS X while working on set of files. However, if you try to process a for loop on file name with spaces in them you are going to have some problem. For loop uses $IFS variable to determine what the field separators are. By default $IFS is set to the space character. There are multiple solutions to this problem.

Set $IFS variable

Try it as follows:

IFS=$(echo -en "\n\b")
for f in *
  echo "$f"


IFS=$(echo -en "\n\b")
# set me
for f in $FILES
  echo "$f"
# restore $IFS

More examples using $IFS and while loop

Now you know that if the field delimiters are not whitespace, you can set IFS. For example, while loop can be used to get all fields from /etc/passwd file:

while IFS=: read userName passWord userID groupID geCos homeDir userShell
      echo "$userName -> $homeDir"
done < /etc/passwd

Using old good find command to process file names

To process the output of find with a command, try as follows:

find . -print0 | while read -d $'\0' file
  echo -v "$file"

Try to copy files to /tmp with spaces in a filename using find command and shell pipes:

find . -print0 | while read -d $'\0' file; do cp -v "$file" /tmp; done

Processing filenames using an array

Sometimes you need read a file into an array as one array element per line. Following script will read file names into an array and you can process each file using for loop. This is useful for complex tasks:

# failsafe - fall back to current directory
[ "$DIR" == "" ] && DIR="."
# save and change IFS
# read all file name into an array
fileArray=($(find $DIR -type f))
# restore it
# get length of an array
# use for loop read all filenames
for (( i=0; i<${tLen}; i++ ));
  echo "${fileArray[$i]}"

Playing mp3s with spaces in file names

Place following code in your ~/.bashrc file:

	local o=$IFS
	IFS=$(echo -en "\n\b")
	/usr/bin/beep-media-player "$(cat  $@)" &

Keep list of all mp3s in a text file such as follows (~/eng.mp3.txt):

/nas/english/Adriano Celentano - Susanna.mp3
/nas/english/Nick Cave & Kylie Minogue - Where The Wild Roses Grow.mp3
/nas/english/Roberta Flack - Kiling Me Softly With This Song.mp3
/nas/english/The Beatles - Girl.mp3
/nas/english/John Lennon - Stand By Me.mp3
/nas/english/The Seatbelts, Cowboy Bebop - 01-Tank.mp3

To play just type:
$ mp3 eng.mp3.txt

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 65 comments so far... add one
CategoryList of Unix and Linux commands
Disk space analyzersncdu pydf
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
65 comments… add one
  • Sergio Dec 9, 2008 @ 21:44

    Hi, I don’t fully understand how this…

    BASH for loop works nicely under UNIX / Linux / Windows and OS X

    works nicely under Windows…

    Oh! btw, thank you.

  • 🐧 nixCraft Dec 9, 2008 @ 22:00

    Install cygwin from

    Install bash and your are done!

  • Jeff Schroeder Dec 10, 2008 @ 4:02

    For the shell equivalent of python’s splitlines, I always did it like this:

    for line in $(< line-with-spaces-between-fields.txt); do

    or while read ... instead of for when the list exceeds $(getconf ARG_MAX)

    Your way works too, but is more typing

  • Amr Hamdy Dec 10, 2008 @ 4:06

    Thanks really so much,
    It’s so useful and I think it’d save me a lot of time and help me do better shell coding..

  • Benjamin Schmidt Dec 10, 2008 @ 8:03

    This is a great blog!

    Instead of using following:

    find . -print0 | while read -d $'' file
      echo -v "$file"

    I just use:

    find . | while read file
      echo "$file"

    Never had problems with it. A filename can impossible contain newline-chars, or am I wrong?

    Best regards,
    Benjamin Schmidt

    • Matthias Jul 26, 2010 @ 18:31

      File names can contain newline characters.

      Gnome for example displays them correctly. Couldn’t manage to create such a file in Gnome. I tested creation in C and Python iirc.

      • Ernesto Aug 25, 2012 @ 9:09

        In bash you can create a file with a newline in the name using, e.g:

        touch $’weirdnfile’

  • 🐧 nixCraft Dec 10, 2008 @ 8:59


    Thanks for sharing your code and ideas.

  • chika.tambun Dec 10, 2008 @ 12:17

    i’d love to play music with mplayer… through cli
    let say that i have song/music folder with many directory inside, how i can play with mplayer with single command. Actually i have one bash script, but i got trouble when facing white space… mplayer wouldn’t play the file

    for i in ` find -name “*mp3″`
    mplayer $i

    any help will be appreciated

  • 🐧 nixCraft Dec 10, 2008 @ 12:21


    find .  -iname "*.mp3" -print0 | while read -d $'' file
      mplayer "$file"
  • Chris F.A. Johnson Dec 10, 2008 @ 15:40

    > A filename can impossible contain newline-chars, or am I wrong?

    A filename can contain newlines. It can contain any character except a slash (/) or an ASCII NUL (0x0).

  • Chris F.A. Johnson Dec 10, 2008 @ 15:45

    # use for loop read all filenames
    > for (( i=0; i do
    > echo “${fileArray[$i]}”
    > done

    If all you want to do is print the contents of the array:

    printf "%sn" "${fileArray[@]}"

    To loop through them, use:

    for i in "${fileArray[@]}"
    : ... whatever

  • chika.tambun Dec 11, 2008 @ 13:24

    great… vivek.gite ^^

    your script just work on one file… then mplayer killed immediately.
    yeah just playing one file only(there are many left).

    on playing progress i can’t get control of mplayer, even i can’t turn up/down volume, go to the next song, etc.

    all i can do is Ctrl+C

    btw thanks

  • 🐧 nixCraft Dec 11, 2008 @ 14:12

    I guess you can try
    mplayer *.mp3

    Or send all files to .playlist.txt
    ls -1 > .playlist.txt
    mplayer -playlist .playlist.txt

  • mhernandez Dec 11, 2008 @ 15:30

    All this information is very useful, but I think that needing it is sympton: ¿shouldn’t you use another language instead?

    Nice post, though

  • Chris F.A. Johnson Dec 11, 2008 @ 21:08

    “All this information is very useful, but I think that needing it is sympton: ¿shouldn’t you use another language instead?”

    Why? It’s straightforward shell scripting.

  • mhernandez Dec 11, 2008 @ 21:46

    opendir(DIR, “.”) or die(“Error opening directory”);
    my @readFiles = readdir(DIR);
    foreach (@readFiles) {

  • Kyle Brandt Dec 16, 2008 @ 19:27

    I don’t think there is a need to reset the IFS variable, all you really need to do to avoid problems with word splitting is to put the variables that appear in the loop body in double quotes (I find this to be a good default habit). Once in double quotes the shell will consider whatever the variable expands to as a single argument and pass it to the program as such.

    For example:
    for i in *.mp3; do rm “$i”; done

    mhernandez: Its not a problem with the shell, its just how it works, the bash shell is based on word splitting.

    • Rob Leach Jul 12, 2010 @ 13:40

      This doesn’t seem to work for me. I’m wondering what I’m doing wrong….

      If I do this:

      $ for file in $(ls | awk -F. ‘{print $1}’); do sox -S “${file}.m4a” “${file}.ogg”; done

      it doesn’t work as I would have expected.

  • Dean Faulkner Jan 7, 2009 @ 16:57

    You can reset the IFS with

    unset IFS

    this way, you do not need to save the state and then recall it from a variable.

  • Jim Eberle Jan 10, 2009 @ 3:47

    Kyle is correct. No need to mess w/ your IFS var.
    Your 2nd example is problematic in a very subtle way


    does not set the variable ‘FILES’ to the names of all the files in /data, it sets it to ‘/data/*’. You can see this w/:

    declare -p FILES

    A very useful technique in all this, is to employ the ‘set’ builtin:

    cd ..; set *.txt; cd ~-
    for f; do
    echo "../$f" "$f"

    This lets you scoop up a file list (w/ nasty names and all), and then move somewhere else to process them.

  • joel Feb 10, 2009 @ 5:30

    i am doing a project in unix shell scripting.
    so my project have messages to be displayed. my problem is that how to add a beep sound to the messages …can any help me to include that also with the coding??pls..its very urgent…i dont know the shell codings…its for my project

  • Reid Feb 19, 2009 @ 17:17

    Chris F.A. Johnson has it right on the nose.

    use a quoted @-array: <code“${fileArray[@]}”

    A quoted array with an @ subscript expands to a list of quoted elements of that array.

    No IFS manipulation required!


  • DoXuS Jul 21, 2009 @ 11:51

    Thanks man, my code is now only 40 lines long, not 136 like before xD^^
    nice blog

  • fvw Aug 26, 2009 @ 4:48

    local o=$IFS
    IFS=$(echo -en “nb”)
    /usr/bin/beep-media-player “$(cat $@)” &
    “$(cat $@)” if you use this I think the IFS down work …
    I think you want $(cat “$@”)

  • Rich Sep 2, 2009 @ 20:38

    Thank you! I found this post most useful.

  • gimi Oct 1, 2009 @ 21:06

    Instead of telling echo to print a char for new line and (probably) bell and then *not* to print a new line, one can just use echo’s default new line output 🙂


    Thanks for your share!

  • cfajohnson Oct 7, 2009 @ 9:45

    Why “IFS=`echo`”? Command substitution is slow (and unnecessary).


    IFS=$’n’ ## bash

  • Brian Nov 13, 2009 @ 5:47

    Amazing! Your notation for creating an array from:
    > fileArray=($(find $DIR -type f))
    is stunning! Thanks for the excellent writeup.

  • xiaoyuhum Nov 26, 2009 @ 7:07

    I just use as following
    with double quotes
    for m in “`ls`”; do echo “$m” ; done

  • cfajohnson Dec 2, 2009 @ 22:36

    for m in "`ls`"; do echo "$m" ; done


    The for command will only see one argument.

    Try this:

    for m in "`ls`"
    echo "$n"
    echo "$m"
    n=$(( $n + 1 ))

    You’ll see that it only goes through the loop once.

    You don’t need a loop for that, and you don’t need ls:

    printf "%sn" *

  • Shreyas Kulkarni Dec 19, 2009 @ 17:52

    excellent post. exactly what i was looking for. i had been facing this space-field-seperator problem for quite a sometime today. had tried many options to circumvent it, but in vain. will try this $IFS approach now.

    thanks a lot for sharing.


  • Chris Thiessen Feb 8, 2010 @ 20:09

    My favorite solution, though it can theoretically overmatch:

    find . | sed -e “s/ /?/g”
    ls | sed -e “s/ /?/g”

    Then you can do things like greps, for loops, whatever equally well:
    grep hello $(ls | sed -e “s/ /?/g”)
    for i in $(find . | sed -e “s/ /?/g) do; ls -l “$i”; done

  • cfajohnson Feb 9, 2010 @ 8:07

    “grep hello $(ls | sed -e “s/ /?/g”)”

    You don’t need sed or ls; use filename expansion:

    grep hello *

    “for i in $(find . | sed -e “s/ /?/g) do; ls -l “$i”; done”

    That will fail if any filenames contain whitespace.

    It is also extremely inefficient to call ls in a loop.

  • piponazo Mar 11, 2010 @ 15:01

    Great post! It has been very useful for me 😀

  • gringo guy Apr 19, 2010 @ 4:18

    Hey, thanks for this! I never did much bash scripting and was trying to figure out how to parse an array from a bash RC file into a Perl variable. I started out writing a long parser hack, but trying to support array entries with spaces was a big headache. Then thought maybe bash should do the work instead, and your examples helped a lot. Here’s a one-liner bash script that’s run using the Perl `backtick` operator.

    $path is the RC file, and $var is the array variable. BASH variables must be escaped, but PERL
    variables must not, and new-line chars have to be added so bash is happy with the string.
    First step is to source the RC file, and next get the length of the array.

    $list = `. $path; L=${#${var}[@]}n for (( i=0; i<${L}; i++ ));n don echo -n ${${var}[$i]},n done`;
    chop( $list ); # strip the trailing comma

    foreach $entry (split(",", $list)) { # Prove that it works
    print "entry: '$entry'n";

    Here's an example of the bash array that this will parse. Cool. Thanks again for your examples.

    ARRAY_VAR=( .bashrc .vimrc "foo bar" .java
    .Xdefaults "other file name" )

  • Kelvin Nicholson Aug 25, 2010 @ 21:40

    Fixed my little script! Cheers for posting this – always nice to learn something new.

  • Dennis Gearon Sep 11, 2010 @ 6:24

    Trying to get the following to work. If I cut and paste the eventual contents of $directoryFiles EITHER in the bash script OR on the command line, it works perfectly. If I try to get it to do it directly in the script, it fails with:

    tar –all the file names– : Cannot stat: No such file or directory

    I”ve tried about every expansion or quoting that I can think of for the $direcotryFiles variable.

    IFS=$(echo -en "nb")
    for file in $( find /home/gearond -maxdepth 1 -type f)
      directoryFiles="$directoryFiles"$file" "
      #echo $file
    tar -cf /tmp/directoryFiles.tar.bz2  $directoryFiles
    • 🐧 nixCraft Sep 11, 2010 @ 8:28

      How about:

      find /home/gearond -maxdepth 1 -type f -print0 | xargs -O -I file your-command-on file

      In your case:

      find . -maxdepth 1 -type f -print0 | xargs -0 -I {} tar -rjvf /tmp/directoryFiles.tar.bz2 {}
      tar -tjvf /tmp/directoryFiles.tar.bz2
  • Paul Grevink Feb 8, 2011 @ 12:08

    Thank you very much, this is very helpful.
    I work with Linux for many year, but until today, I did not know this.

  • jcubic Mar 7, 2011 @ 17:03

    What is the difference between

    IFS=$(echo -en "nb")



    Which do exactly the same (but don’t call sub shell)

  • Chris F.A. Johnson Mar 7, 2011 @ 17:50

    They do not do the same thing.

    The first assigns a newline and a backspace to IFS; the second assigns an empty string.

    The first assignment can be done more efficiently with:

  • Stefan Mueller Jun 4, 2011 @ 19:45

    Thanks to all contributors of this outstanding discussion!

  • 8ohmh Jul 23, 2011 @ 14:02

    Thanks for your tip. I was not thinking anymore about IFS. Here’s a tip to remove unwanted characters in filenames:

    IFS=$(echo -en "nb")
    for f in $FILES
    	#echo	"$f"
    	mv -b --strip-trailing-slashes "$f" "$FILENAME"

    replaces ?, % and + with _ (Useful if you copy FAT32 files to linux and back)

  • Rud Holmgren Aug 14, 2011 @ 6:07

    For simple operations on multiple files you can use the -exec option on find:

    find . -iname ‘*.avi’ -exec mv {} /Some/Where/Else/ ;

    This command recursively finds all .avi files in the current directory and moves them to folder /Some/Where/Else. The curly brackets {} are substituted with file name. Consult the man page for more details.

  • zerocool Sep 20, 2011 @ 0:59

    array=($(mysql –host= –user=XXXX –password=XXXX -s -N -e ‘use xbmc_video; SELECT c22 FROM movie, files WHERE files.idFile=movie.idFile ORDER BY idMovie DESC LIMIT 10;’))

    how can i get rid of spaces in this array

    • Chris F.A. Johnson Sep 22, 2011 @ 17:10
      array=( "${array[@]// /}" )
  • Tom Thurman Jan 23, 2012 @ 20:14

    Thanks for the very clear explanation!

  • amrutha Apr 24, 2012 @ 14:02

    Hello there,

    I tried the code for storing the filenames into an array variable with a few modifications:

    # failsafe - fall back to current directory
    #[ "$DIR" == "" ] && DIR="."
    # save and change IFS
    cd $DIR
    # read all file name into an array
    fileArray = ( $(`ls -l`) )
    # restore it
    # get length of an array
    echo $tLen
    # use for loop read all filenames
    for (( i=0; i<${tLen}; i++ ));
      echo "${fileArray[$i]}"

    But, i have been running into errors on this:

    error: syntax error at line 12: `(' unexpected

    I have no clue how to proceed with this problem. Could anyone tweek this problem?


  • Chris F.A. Johnson Jun 18, 2012 @ 18:30
    fileArray = ( $(`ls -l`) )

    should be

    fileArray=( * )
  • manolo Aug 28, 2012 @ 17:28

    Hi there,
    I used the above example script for concatenating multiple files which works fine for me if the directory structure contains no spaces.However now I am facing a dierctory structure that does have spaces. Setting the IFS doesn’t seem to help here.
    The directory structure I am facing is such: ./CH 0000010240/A10/21MT/21mt#001.csv and I want to concatenate all .csv files I find. Here is my current version of the script which I am running on OS X:

    # failsafe - fall back to current directory
    [ "$DIR" == "" ] && DIR="."
    # save and change IFS
    # read all file name into an array
    fileArray=($(find $DIR -type f))
    # restore it
    # get length of an array
    # use for loop read all filenames
    for (( i=0; i> all.csv

    Thanks for any hints.

  • Chris F.A. Johnson Sep 3, 2012 @ 4:49
    > #!/bin/bash
    > DIR="$1"
    > # failsafe - fall back to current directory
    > [ "$DIR" == "" ] && DIR="."


    > # save and change IFS
    > IFS=$'n'
    > # read all file name into an array
    > fileArray=($(find $DIR -type f))
    > # restore it
    > # get length of an array
    > tLen=${#fileArray[@]}
    > # use for loop read all filenames
    > for (( i=0; i> all.csv

    for file in “${filearray[@]}”
    : do something with “$file” (in quotes)

    > done
  • Ben Sep 23, 2012 @ 8:12

    Nixcrift FTW again. Good job.

  • Tobias Sep 28, 2012 @ 14:42

    Very helpful. Thanks

  • Massimo Oct 18, 2012 @ 7:23

    It’s very helpful. Thank you

  • Sapan May 13, 2013 @ 7:04

    This can be simpler

    for f in “` `”

    just the ” around the comand and that is it

  • Megabyte Jun 5, 2013 @ 3:16

    Can anyone explain to me what the -v’s, used with echo and cp, in the “Using old good find command to process file names” section above, are for/do?

  • Alex Oct 21, 2013 @ 11:21

    Thank you very much Author for sharing these knowledge with other people!

  • David A. Wheeler Nov 6, 2013 @ 4:16

    The filename handling examples are wrong in several ways. Filenames can include newlines, backslashes, backspaces, tabs, asterisks, and other weirdness, which this doesn’t handle.

    # For example, wrong – doesn’t handle filenames with n or b
    IFS=$(echo -en “nb”)
    for f in *
    echo “$f”

    For more on how to do it correctly, see:

  • zephyrothic Jan 27, 2015 @ 21:57

    Excelente! Tank You!!!

  • Caifo Nov 19, 2015 @ 8:44

    Thanks! you’re my savior.

  • TR Jan 11, 2016 @ 21:25

    Thanks. I had been trying to do:
    > for f in `ls`;
    > for f in $( ls );
    Both were problematic. But
    > for f in *; works, regardless of $IFS AFAICT.

  • TR Jan 11, 2016 @ 21:26

    This site should have a bitcoin donation link.

  • Rod McLaughlin Jun 9, 2016 @ 2:12

    Thanks for this. Worked a treat. I wanted to delete dozens of folders in iTunes containing the word “Riddim”, and ended up with this:


    IFS=$(echo -en “nb”)

    for d in `ls` ; do g=`ls “$d” | grep Riddim` ; if [ “” != “$g” ] ; then echo “$d – $g” ; fi ; done


  • Iria Jun 10, 2016 @ 15:44

    Every time i forget something and promptly Google for it, I land on your website! Thanks for all your efforts. Brilliant.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum