Tonight I was trying to cleanup my macports installation by uninstalling the packages that are no longer active. I decided to write a script to do this, instead of manually uninstalling them one by one. But in writing the script I came across something I had never seen and the google didn’t give me a clear answer so I thought I would share.
A typical for loop might look like:
-
$ for file in `ls`
-
> do
-
> echo $file
-
> done
And this assumes there are no spaces in any of the files returned by ls. I did not know this. So I started doing something similar with this:
-
$ for package in `port installed | awk 'NF==2{print $0}' `
-
> do
-
> echo $package
-
> done
But I got output that looked like this:
-
curl
-
@7.17.1_0
-
gettext
-
@0.17_2
And wanted output like this:
-
curl @7.17.1_0
-
gettext @0.17_2
The problem is the awk output had spaces in it which were split by the for loop processing. And well to handle the spaces as desired you need to pipe the output to a while loop like so:
-
$ port installed | awk 'NF==2{print $0}' | while read pakage
-
> do
-
> sudo port uninstall $package
-
> done
And now $package is what I expect including the spaces, and my macports installation is a little cleaner.
