5

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?

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
chop
  • 461
  • 1
  • 6
  • 16

3 Answers3

9

Add IFS=$'\n' to the start but don't add double quotes around the variable in the for loop. The input field separators include spaces and tabs by default.

Lri
  • 26,768
  • 8
  • 84
  • 82
4

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
Lee Netherton
  • 21,347
  • 12
  • 68
  • 102
  • Yes this is a much better approach @Lee, I see it makes sense. I managed to get this working with the addition of `IFS=$'\n'` thanks to @Lauri so therefore I also stripped out the sed code – chop Nov 02 '12 at 17:21
1

Try enclosing the variables with double quotes:

servicesAre=`networksetup -listallnetworkservices | tail -n +2 | sed 's/.*/"&"/'` ; 
for interface in "$servicesAre"; do 
      printf " \nFor $interface we have:\n \n" ; 
      networksetup -getdnsservers "$interface" ; 
done
sampson-chen
  • 45,805
  • 12
  • 84
  • 81
  • Single quotes will not work. You should always use double quotes around all your variable interpolations, unless you specifically require the shell to do whitespace splitting on the values. – tripleee Nov 02 '12 at 15:45
  • Thanks for the help so far. I get the list passed through ok now, but the networksetup command attempts to run on the whole list rather than line by line... What am I doing wrong? – chop Nov 02 '12 at 16:12