4

I am trying to include this

du -s *|awk '{ if ($1 > 3000) print }'

in a shell script, but I want to parameterize the 3000. However, since the $1 is already being used, I'm not sure what to do. This was a total failure:

size=$1
du -s *|awk '{ if ($1 > $size) print }'

How can I pass a parameter in place of 3000 in the first script above?

3
  • {if ($1 > $size) print} is equivalent to $1>size Commented Mar 1, 2010 at 11:51
  • @ghostdog74, well this `size=$1; du -s *|awk '{ $1>size }' doesn't work... not sure what your comment means Commented Mar 1, 2010 at 12:14
  • i mean in awk, {if ($1 > $size) print} is the same as $1>size. see my answer for clearer picture. Commented Mar 1, 2010 at 23:38

4 Answers 4

4

when passing shell variables to awk, try to use the -v option of awk as much as possible. This will be "cleaner" than having quotes all around

size="$1"
du -s *| awk -v size="$size" '$1>size'
Sign up to request clarification or add additional context in comments.

2 Comments

The quotes in size="$1" are unnecessary. Simple variable assignments (FOO=$BAR) don't need quotes.
its my habit sometimes. no harm putting it in anyways.
3

Single quotes inhibit expansion, so:

du -s *|awk '{ if ($1 > '"$1"') print }'

2 Comments

this is a great answer. could you include why it's better/worse/same as du -s *|awk '{ if ($1 > '$1') print }'?
If the first argument contains a space (it shouldn't, but I prefer not to hope things go right) then omitting the double quotes will cause awk to not necessarily work as desired.
3
size=$1
du -s *|awk '{ if ($1 > '$size') print }'

2 Comments

Be a little careful, as passing a parameter with a space in it will cause this to fail. This may of course be desirable.
But using your answer you can also just nix the $size and use $1 where you used $size. Anything wrong with that option?
1

You can set awk variables on its command line:

du -s * | awk '{ if ($1 > threshold) print }' threshold=$1

2 Comments

only exception using this method is that threshold will not have value in BEGIN{} block.
@ghostdog74 what do you miss without the BEGIN{} block?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.