简体   繁体   English

使用带空格的变量进行bash for循环

[英]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. 我在Mac OS 10.7.x上,需要询问网络服务,以报告针对服务定义的接口以及针对每个接口设置的dns服务器。

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? 我如何通过这些?

Add IFS=$'\\n' to the start but don't add double quotes around the variable in the for loop. IFS=$'\\n'添加到开头,但不要在for循环中的变量周围添加双引号。 The input field separators include spaces and tabs by default. 输入字段分隔符默认包含空格和制表符。

The problem is that you want the for loop to loop once per line, but for loops in bash loop once per argument. 问题是你希望for循环每行循环一次,但是对于bash循环中的循环每个参数一次。 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: 为避免这种情况,我建议抛弃for循环和变量,然后使用read和while循环:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM