0

If I am trying to look up which host bus is the hard drive attached to, I would use

ls -ld /sys/block/sd*/device

it returns

lrwxrwxrwx 1 root root 0 Oct 18 14:52 /sys/block/sda/device -> ../../../1:0:0:0

Now if I want to parse out that "1" in the end of the above string, what would be the quickest way?

Sorry I am very new to shell scripting, I can't make full use of this powerful scripting language.

Thanks!

2 Answers 2

2

Split with slashes, select last field, split it with colons and select first result:

ls -ld /sys/block/sd*/device | awk -F'/' '{ split( $NF, arr, /:/ ); print arr[1] }'

It yields:

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

2 Comments

can you explain "{ split( $NF, arr, /:/ ); print arr[1] }"?
Yes. It's very simple. $NF is the last field (1:0:0:0) and arr is an array variable where it saves each part split, so I access to the first one.
1

Try doing this :

$ ls -ld /sys/block/sd*/device |  grep -oP '\d+(?=:\d+:\d:\d+)'
0
2
3

or

$ printf '%s\n' /sys/block/sd*/device |
    xargs readlink -f |
    grep -oP '\d+(?=:\d+:\d:\d+)'

and if you want only the first occurence :

grep ...-m1 ...

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.