IFS Cheatsheet

The IFS variable is the for loop delimiter. By default its set to space,tab,newline (first spaces are looked at as delimiters, and then tabs, and then newlines). This will cause problems for a for loop that has to iterate thru file names with spaces (“The long boring story.pdf”), and it will split up files with spaces thus causing errors in your scripts such as “file doesnt exist” (because it couldnt find “The”, “boring”, or “story.pdf” files – unless you got lucky and randomly have those files)

# IFS default (space, tab, newline)
IFS=$' \t\n'
# IFS new line (best for iterating thru files & folders) 
IFS=$'\n'
IFS=$(echo -en "\n\b")  # both methods work, id just remember the one above as its simpler
# View current IFS
printf %q "$IFS"

 

Leave a Reply

Your email address will not be published. Required fields are marked *