In computational chemistry research, organizing large datasets is essential. To streamline archiving selected files while preserving folder structures, I wrote a Bash script that compresses files based on extensions, facilitating archival of simulation results, inputs, and other critical data while excluding unnecessary files.
The complete code of the script is given below:
#!/bin/bash
usage() {
echo "Usage: $0 -ext [extensions] -f [folder]"
echo " -ext List of file extensions to include in the zip without the dot (e.g., xyz inp out)"
echo " -f Target directory to zip"
exit 1
}
exit_with_message() {
echo "$1"
exit 1
}
# Initial check for no arguments
if [ "$#" -eq 0 ]; then
echo "No arguments provided. You will be prompted to enter the necessary information."
# Prompt for extensions
echo "Enter file extensions to include (space-separated, no dots, e.g., xyz inp out):"
read -ra extensions
if [ ${#extensions[@]} -eq 0 ]; then
exit_with_message "No extensions provided. Exiting."
fi
# Prompt for folder
echo "Enter the target folder to zip:"
read folder
if [ -z "$folder" ]; then
exit_with_message "No folder provided. Exiting."
fi
else
# Initialize variables
declare -a extensions
folder=""
# Parse command line arguments
while [[ "$#" -gt 0 ]]; do
case $1 in
-ext) shift
while [[ "$#" -gt 0 && "${1:0:1}" != "-" ]]; do
extensions+=("${1#.}")
shift
done ;;
-f) shift
folder="${1%/}"
shift ;;
*) echo "Unknown parameter passed: $1"
usage ;;
esac
done
# Verify if extensions and folder are properly specified
if [ ${#extensions[@]} -eq 0 ] || [ -z "$folder" ]; then
exit_with_message "Error: Missing required parameters. Exiting."
fi
fi
# Check if the specified folder exists
if [ ! -d "$folder" ]; then
exit_with_message "Error: The specified folder '$folder' does not exist. Exiting."
fi
# Prepare the find command with dynamic inclusion of file extensions
cmd="find $folder \( -false"
for ext in "${extensions[@]}"; do
cmd+=" -o -name '*.$ext'"
done
cmd+=" \) -print"
# Run the find command and zip the results
if eval $cmd | zip -@ "${folder}.zip" -x "*/.DS_Store"; then
echo "${folder}.zip has been created with the specified file types."
else
exit_with_message "Failed to create zip file. Exiting."
fi
Download Link
How to Use the Script
Save the Script: Save the script to a file, e.g., zip_by_extension.sh.
Make the Script Executable: Run chmod +x zip_by_extension.sh to make the script executable.
Run the Script: Use the following command to run the script:
./zip_by_extension.sh -ext txt log csv -f your_directory
This command will create a your_directory.zip file containing only the .txt, .log, and .csv files from the your_directory folder and its subfolders, preserving the directory structure. If the script is run without arguments, it will ask to input the extensions and folder through an interactive prompt.
Leave a Reply