bash for loop using variables with spaces

bash, for-loop, macos, spaces

Solution

The problem is that you want the for loop to loop once per line, but for loops in bash loop once per argument. By enclosing your variable in quote marks you compound it into one argument. To avoid this, I recommend ditching the for loop and variable and use `read` and a while loop instead:

networksetup -listallnetworkservices | tail -n +2 | sed 's/.*/"&"/' |
while read interface; do 
    printf " \nFor $interface we have:\n \n" ; 
    networksetup -getdnsservers $interface ; 
done

Problem

I am on Mac OS 10.7.x and needing to interrogate network services to report on which interfaces are defined against a service and which dns servers are set against each. ``` servicesAre=`networksetup -listallnetworkservices | tail -n +2 | sed 's/.*/"&"/'` ; for interface in $servicesAre ; do printf " \nFor $interface we have:\n \n" ; networksetup -getdnsservers $interface ; done ``` My problem is the spaces in the initial variable list of interfaces: ``` "USB Ethernet" "Display Ethernet" "Wi-Fi" "Bluetooth PAN" ``` How do I pass those through?

Original source