Skip to content

Instantly share code, notes, and snippets.

@byteme206
Last active December 20, 2018 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save byteme206/b6244d76d2c4b131219e548dc11b6b5a to your computer and use it in GitHub Desktop.
Save byteme206/b6244d76d2c4b131219e548dc11b6b5a to your computer and use it in GitHub Desktop.
Quick example
#!/usr/bin/env sh
# Add a sanity check to make sure that the required arguments are there when the script was called
if [[ -z $2 || -z $1 ]]; then # The "-z" flag tests for a null value
echo "Sorry, but you need to provide a source and destination directory, like this:"
echo " ./filemover.sh source_dir destination_dir"
exit 1
fi
# Define the variables that we will use to control the script execution
SRC_DIR=$1 # Reads the source directory as the first script argument
DEST_DIR=$2 # Reads the destination directory as the second script argument
PREPEND=$(date "+%Y-%m-%d-%H:%m") # Sets the prepend date as "now" in the format YYYY-MM-DD-hh:mm
# Beginning with SRC_DIR and including any subdirectories, identify all .txt and .zip files
for i in `find $SRC_DIR -type f -name "*.txt" -o -name "*.zip"`; # Builds an array (including subdirectories) of matching files and iterates over them one at a time
do
fname=`basename $i` # Strips off the path portion of "i" so that we can rename it easily
nname="$PREPEND-$fname" # Assembles the "New name" for the file in the destination
echo "Copying $fname to $DEST_DIR/$nname"
cp $i $DEST_DIR/$nname # Performs the actual copy
done
# Return the exit code to the shell so we know whether we succeeded or not
exit $?
@byteme206
Copy link
Author

This is a VERY incomplete example and addresses the question, "how do I copy files with one of two specific extensions from one directory to a different destination, while prepending the copy date to the filename in the destination. It assumes that you'll want to walk subdirectories, but does not maintain the directory structure at the destination.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment