Monday, December 22, 2008

Bash Scripting with Spaces

From time to time I have I run into a space issues when trying to write bash scripts.  This website was the first solution that made sense.
  1. cat /var/lib/dpkg/info/skype.list
  2. for i in `cat /var/lib/dpkg/info/skype.list`; do echo rm $i; done
Modified command:
  1. IFS=$(echo -en "\n\b"); for i in `more /var/lib/dpkg/info/skype.list`; do echo rm \"$i\"; done
Note: the above command didn't work like I wanted it to and then I figured out why I couldn't delete skype from aptitude, it was only installed using gdeb or dpkg -i.

BASH Shell: For Loop File Names With Spaces
BASH Shell: For Loop File Names With Spaces

by Vivek Gite [Last updated: December 9, 2008]

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:

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

OR

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

No comments:

Post a Comment