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?

3
  • echo doesn't care whether or not its argument exists in the filesystem. Commented Jul 1, 2013 at 2:04
  • Do an ls -l on /sys/class/net/wlan0/operstate Commented Jul 1, 2013 at 2:06
  • The file link to other devices (hardware names), but cat does work? Commented Jul 1, 2013 at 2:09

2 Answers 2

2

First, you should not be repeating /sys/class/net/ inside the loop since $f will already contain those directories.

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

Next, the $(...) inside the loop needs to go. There's no need to capture cat's output.

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

Now $(ls ...) can be done away with with a simple wildcard:

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

Finally, the entire loop can be replaced with a single call to cat.

cat /sys/class/net/*/operstate
Sign up to request clarification or add additional context in comments.

1 Comment

@Edouard I honestly don't know. Is that the exact output from your shell? Those don't look like the right error messages. I would have expected cat: /sys/class/net//sys/class/net/eth0/operstate: No such file or directory
0

Your bash script is trying to cat file called operstate in each subdirectory of /sys/class/net, and the file is not found. In the second example your simply echoing a string which prints out just fine.

Comments

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.