6

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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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

1 Comment

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
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

2 Comments

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.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.