1

I want to check if the size of the newest file is greater than 2 MB:

test $(ls -st | head -n2 | tail -n1 | awk '{print $1}') -gt 2097152 && echo "true"

Is there a more efficient or elegant way to do this?

I tried to further pipe the output of awk to

| test {} -gt 2097152

but get

bash: test: {}: integer expression expected

Then

| test {}>"2097152"

yields always 'true' so I came up with the construct

test $(...) -gt 2097152
1
  • Note that ls -s doesn't report the size but the disk usage. Commented Mar 29, 2020 at 9:54

2 Answers 2

3

There might be better ways than ls for getting the newest file, but most of what you do can be done just in awk:

ls -st | awk 'NR == 2 && $1 > 2097152 {print "true"}'
  • NR == 2 - in the second line
  • $1 > 2097152 - when the first column is greater than 2097152
3

With zsh:

set -- *(.om[1]) *(N.L+2097152om[1])
if [[ $1 = $2 ]]; then
  printf '%s\n' "The apparent size of the newest non-hidden regular file in the current" \
                "directory ($1) is strictly greater than 2MiB."
fi

If you want to include hidden directories, add D to both glob qualifiers. If you want to consider non-regular files (directories, symlinks, devices...), remove .

The idea is to expand both these globs:

  1. the list of non-hidden regular (.) files, ordered by modification time, limited to one ([1]).
  2. the same but limited to files whose Length is strictly greater (+) than 2097152 (but enabling NullGlob so it's not a fatal error if there's no match).

And our condition is meant if both globs expand to the same file.

Note that ls -s, doesn't report the size of files but their disk usage (in number of 512-byte units, or KiB or other depending on the ls implementation and/or the environment). ls reports the file size in it long output format (ls -l or ls -n (or -o/-g with some implementations)).

Another option is to use zsh's stat builtin to get the size (or disk usage) of the newest file:

zmodload zsh/stat
if
  stat -LH s -- *(.om[1]) &&
    ((s[size] > 2097152))
then
  printf '%s\n' "The apparent size of the newest non-hidden regular file in the current" \
                "directory ($1) is strictly greater than 2MiB."
fi

Or:

zmodload zsh/stat
if
  stat -LH s -- *(.om[1]) &&
    ((s[blocks] > 2097152))
then
  printf '%s\n' "The newest non-hidden regular file in the current directory" \
                "($1) uses more than 2097152 512-byte units of disk space."
fi

(in other words, its disk usage is more than 1GiB)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .