1

I wrote the following command to list all files in and below '~' by order of file size. It seems to work fine:

find ~ -printf "%k KB %p\n" | sort -nr

Now I want to put this is a shell script and loop through the results to do more processing.

I got this to work with a simple 'ls' command:

dir="/home/myusername"
cmd='ls'
for i in `$cmd`
do
  echo $i
done

But this doesn't work:

dir="/home/myusername"
cmd='find $dir -printf "%k KB %p\n" | sort -nr'
for i in `$cmd`
do
  echo $i
done

I've also tried using escape characters in front of the double-quotes, but that didn't work either ...

dir="/home/myusername"
cmd='find $dir -printf \"%k KB %p\n\" | sort -nr'
for i in `$cmd`
do
  echo $i
done

Any ideas what I'm doing wrong?

6
  • @BroSlow hi -- thanks for the help, but that was a typo in my question -- I changed the "~" to "$dir" -- thx Commented Jan 27, 2014 at 0:38
  • No problem, also see stackoverflow.com/a/11366230/3076724 to fix your find syntax, otherwise it will break on spaces/weird characters. Commented Jan 27, 2014 at 0:38
  • possible duplicate of find while loop with files containing spaces in bash Commented Jan 27, 2014 at 0:41
  • @thatotherguy thanks, but I don't think it's the same issue. I'm just trying to run the admitted tricky command and the escape characters aren't working Commented Jan 27, 2014 at 0:53
  • @RobertHume The escape characters aren't working because your approach is fundamentally flawed. To loop over results, use the linked question's method (and sort -z to sort). Commented Jan 27, 2014 at 1:00

3 Answers 3

3

Try this while loop with find in BASH:

while read -r f; do
    echo "$f"
done < <(find "$dir" -printf "%k KB %p\n" | sort -nr)
Sign up to request clarification or add additional context in comments.

Comments

1

To execute simple commands, you can pipe the results of find into xargs:

find ~ -printf "%k KB %p\n" | sort -nr | xargs -l -i echo '{}'

-l: makes xargs process one line at a time.

-i: substitutes each occurrence of {} with the output of the pipe.

Comments

0

This should work (see https://stackoverflow.com/a/11366230/3076724 for an explanation of why not to use original syntax)

find "$dir" -printf "%k KB %p\n" | sort -nr |  while read -r i; do
  echo "$i"
done

4 Comments

@RobertHume You're definitely running it as a bash script?
I think so -- how can I be 100% certain?
@RobertHume Put ps -o cmd= -p $$ inside the script. Or just echo $0 from your shell before you run it to see what shell you're using, or just run it as bash whateverscript
Isn't the default delimiter of while read syntax a newline character?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.