0

Please give me any shell bash script that will help me doing following task:

if last added 4 file size of a directory are same with each other then exit other wise continue

Example :

ls -l $dir_path | awk '{print $5}' | tail -4

if the 4 printed values are same to each other then exit otherwise continue.

  • can you explain little bit more, it's not clear to me – Rahul Jul 22 '16 at 12:18
  • 6
    Unix & Linux SE is not a script writing service. – a CVn Jul 22 '16 at 12:27
  • 3
    In order to get help with you script writing abilities, please show us what you tried and give details on why it doesn't work. – Julie Pelletier Jul 22 '16 at 12:29
1
zsh -c 'zmodload zsh/stat
  [[ $(zstat -N +size -- *(.om[1,4])) =~ $'\''(.*)\n\\1\n\\1\n\\1'\'' ]]' && exit

Would exit if the 4 newest non-hidden regular files in the current directory all have the same size.

On a GNU system, you could also do:

find . -maxdepth 1 ! -name '.*' -type f -printf '%T@ %s\n' |
  sort -rn |
  awk 'NR == 1 {v = $0}; v != $0 {exit}; NR == 4 {exit 1}' || exit

POSIXly:

ls -tnq -- "$dir_path" |
  awk '!/^-/ {next}
       n++ == 0 {v = $5}
       v != $5 {exit}
       n == 4 {exit 1}' || exit

If like in your own approach, instead of the 4 newest ones, you want the last 4 (regardless of whether they're regular files or symlinks or sockets...) in the ls output (which is an alphabetically sorted list), you can do (still POSIXly):

ls -rnq -- "$dir_path" |
  awk 'NR == 1 {next}
       NR == 2 {v = $5}
       v != $5 {exit}
       NR > 4 {exit 1}' || exit
| improve this answer | |
  • 2
    OP wants bash, not zsh... – a CVn Jul 22 '16 at 12:41
  • @MichaelKjörling well spotted, updated. – Stéphane Chazelas Jul 22 '16 at 12:51
  • Well, that's one way of solving that... :-) – a CVn Jul 22 '16 at 13:07
0

Use ls -c to sort by ctime, and uniq to see if they're the same.

ls -crntq | tail -4 | awk '{print $5}' | uniq -c | grep -q "^\s*4\s" && exit
| improve this answer | |
  • Note that ls -s gives the file disk usage, not the file size. – Stéphane Chazelas Jul 22 '16 at 13:47
  • You'd want to pass the -q option to avoid problems with filenames containing newline characters. – Stéphane Chazelas Jul 22 '16 at 13:48
  • @StéphaneChazelas Bah, I'll have to use the longer output for the size-in-bytes. My version of ls (GNU coreutils 8.21) had already changed the newlines to ?, so -q made no difference, but I'll include that for completeness. – JigglyNaga Jul 22 '16 at 14:07
  • Without -q, the newline is only turned to ? when the output doesn't go to a terminal, so typically, not when fed to tail via a pipe. – Stéphane Chazelas Jul 22 '16 at 14:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.