Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash for loop using variables with spaces

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?

like image 493
chop Avatar asked Dec 11 '22 21:12

chop


2 Answers

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.

like image 132
Lri Avatar answered Dec 29 '22 09:12

Lri


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
like image 35
Lee Netherton Avatar answered Dec 29 '22 08:12

Lee Netherton