1

I need some help . I have this command

df -h | awk '/md2/' | awk '{print $5}'

I want "/md2/" to set it in variable . search="/md2/" using

df -h | awk '$search' | awk '{print $5}'

gives me no response, how can I make this.

1 Answer 1

3

Use:

search='md2'
df -h | awk -v x="$search" '$0~x{print $5}'

How it works:

  • -v x="$search"

    This tells awk to define an awk variable x to have the value of $search.

  • $0~x{print $5}

    $0 ~ x tells awk to select lines that match the regex in variable x. For the selected lines, field 5 is printed.

Discussion

df -h | awk '$search' | awk '{print $5}'

The above won't work because $search is inside single-quotes and that stops bash from substituting in for the value of $search. You can see this with:

$ search='/md2/';  echo awk '$search'
awk $search

The following will work:

search='/md2/'
df -h | awk "$search" | awk '{print $5}'

Here, $search is inside double-quotes and bash will expand variables that are in double-quotes.

There are still two issues with this:

  1. awk "$search" is potentially dangerous. Awk will execute whatever the contents of $search are. Unless you are very sure about what the contents will be, this could result in mangled or deleted files, etc.

  2. Two uses of awk are unnecessary and slow. Both actions, selecting a line and printing a field can be done in one invocation of awk.

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

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.