Blue42
Blue42

Reputation: 139

What do these lines of shell script do?

Could someone provide a good explanation of what is happening n this code?

find ./ \
  -name "myfile.`date +%Y%m%d`*" \
  -size +10 \
  -exec mv {} ./"myfile.`date +%Y%m%d`.gz" \; \
  2>/dev/null
status=$?

Upvotes: 0

Views: 55

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295403

Files under the current directory whose names start with myfile.${current_date} (where ${current_date} is the date in YYYYmmdd form) are having .gz added to the end of their names, in a moderately buggy fashion.

To break it down line-by-line:

find ./ \                           # find files under the current directory
  -name "myfile.`date +%Y%m%d`*" \  # ...only if their name starts with "myfile."
                                    #    followed by the current date as of when
                                    #    this command is started
  -size +10 \                       # ...and only if they're larger than 10
                                    #    512-byte blocks
  -exec mv {} ./"myfile.`date +%Y%m%d`.gz" \; \
                                    # ...and append ".gz" to their names
  2>/dev/null                       # ...and discard any error messages.

status=$?                           # store the exit status of the previous
                                    # ...command in the variable named "status".

By the way, running date twice this way means that if this is started next to a midnight boundary, the output files could actually have different dates on them than the input files; that makes this command quite dangerous. Moreover, it doesn't preserve the source directory; to prevent recursion, it would need to add a -maxdepth 1 argument to find.

This is also dangerous as it discards suffixes -- if you had multiple files starting with the myfile.${date} prefix, all but one would be silently deleted.

Upvotes: 2

Related Questions