4

I am not understanding how this doesn't work:

ls /sys/class/net/wlan0
addr_assign_type  broadcast  device   flags    iflink     netdev_group  queues
subsystem  uevent  addr_len carrier    dormant  ifalias  link_mode  **operstate**
speed  tx_queue_len address  dev_id  duplex   ifindex  mtu  power statistics  


for f in $(ls /sys/class/net/); do $(cat /sys/class/net/${f}/operstate); done
cat: /sys/class/net/eth0/operstate: No such file or directory
cat: /sys/class/net/lo/operstate: No such file or directory
cat: /sys/class/net/wlan0/operstate: No such file or directory 

I guess $f is not expanded in time for cat. I tried with quotes, like "$f", but still it didn't work.

This does work OK:

for f in $(ls /sys/class/net/); do echo /sys/class/net/${f}/operstate; done
/sys/class/net/eth0/operstate
/sys/class/net/lo/operstate
/sys/class/net/wlan0/operstate

And:

cat  /sys/class/net/eth0/operstate 
up

What have I missed? Why can't cat see the files in the loop?

4

2 回答 2

2

首先,您不应该/sys/class/net/在循环内重复,因为$f已经包含这些目录。

for f in $(ls /sys/class/net/); do $(cat ${f}/operstate); done

接下来,$(...)内部循环需要去。无需捕获 cat 的输出。

for f in $(ls /sys/class/net/); do cat ${f}/operstate; done

现在$(ls ...)可以用一个简单的通配符取消:

for f in /sys/class/net/*; do cat ${f}/operstate; done

最后,整个循环可以用一个对 cat 的调用来替换。

cat /sys/class/net/*/operstate
于 2013-07-01T02:10:53.503 回答
0

您的 bash 脚本试图在 的每个子目录中cat调用文件,但找不到该文件。在第二个示例中,您只需输入一个打印出来的字符串即可。operstate/sys/class/netecho

于 2013-07-01T02:05:57.920 回答