Created
August 14, 2024 12:29
-
-
Save martijnengler/62af86bf7a0f92399b13dcfd3d7f1a50 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env zsh | |
# Script Name: copy-to-similar-dir.zsh | |
# Description: Copies a file to a destination directory, using one of the parent folder names as the destination folder name | |
# Use case is with Hazel, which only has partial support for this functionality | |
# Usage: ./copy-to-similar-dir.zsh /path/to/source/file /path/to/destination/levels_up | |
# Exit immediately if a command exits with a non-zero status. | |
set -e | |
# Function to display the usage message. | |
print_usage() { | |
echo "Usage: $1 /path/to/source/file /path/to/destination levels_up" | |
echo "" | |
echo "Example: $1 /a/b/c/d/e/file.ext ~/1/2/ 1" | |
echo "" | |
echo "This would copy file.ext to ~/1/2/e/" | |
exit 1 | |
} | |
# Check if the number of arguments is exactly 3. | |
if [ "$#" -ne 3 ]; then | |
print_usage "$0" | |
exit 1 | |
fi | |
# Assign arguments to descriptive variables. | |
source_file="$1" | |
destination_base="$2" | |
levels_up="$3" | |
# Validate that the source file exists. | |
if [ ! -f "$source_file" ]; then | |
echo "Error: Source file '$source_file' does not exist." | |
exit 1 | |
fi | |
# Validate that levels_up is a non-negative integer. | |
if ! [[ "$levels_up" =~ ^[0-9]+$ ]]; then | |
echo "Error: 'levels_up' must be a non-negative integer." | |
exit 1 | |
fi | |
source_file="$(realpath "$source_file")" | |
destination_base="$(realpath "$destination_base")" | |
parent_directory="$(dirname "$source_file")" | |
for ((i = 1; i < levels_up; i++)); do | |
parent_directory="$(dirname "$parent_directory")" | |
done | |
folder_name="$(basename "$parent_directory")" | |
destination_directory="$destination_base/$folder_name" | |
mkdir -p "$destination_directory" | |
cp "$source_file" "$destination_directory" | |
echo "File '$source_file' has been copied to '$destination_directory'." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment