views:

128

answers:

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?

+2  A: 

Single quotes inhibit expansion, so:

du -s *|awk '{ if ($1 > '"$1"') print }'
Ignacio Vazquez-Abrams
this is a great answer. could you include why it's better/worse/same as `du -s *|awk '{ if ($1 > '$1') print }'`?
Yar
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.
Ignacio Vazquez-Abrams
+3  A: 
size=$1
du -s *|awk '{ if ($1 > '$size') print }'
ar
this is cool, thanks! Also works with '$1' of course.
Yar
Be a little careful, as passing a parameter with a space in it will cause this to fail. This may of course be desirable.
ar
But using your answer you can also just nix the $size and use $1 where you used $size. Anything wrong with that option?
Yar
+4  A: 

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'
ghostdog74
The quotes in size="$1" are unnecessary. Simple variable assignments (FOO=$BAR) don't need quotes.
Idelic
its my habit sometimes. no harm putting it in anyways.
ghostdog74
+1  A: 

You can set awk variables on its command line:

du -s * | awk '{ if ($1 > threshold) print }' threshold=$1
mouviciel
only exception using this method is that `threshold` will not have value in BEGIN{} block.
ghostdog74
interesting, cool way to do it.
Yar
@ghostdog74 what do you miss without the BEGIN{} block?
Yar