-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenlinks
82 lines (66 loc) · 2.38 KB
/
genlinks
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/bin/bash
# --------------------- genlinks ---------------------
# A script for generating symlinks.
# If a directory is passed, the script will duplicate its
# structure to the destination with symlinks of the original files.
#
# Usage:
# genlinks <Source File / Directory> <Destination Directory> [<File Extensions>...]
#
# Arguments:
# 1. File / Directory - A file or directory to create links from.
# 2. Destination Directory - Destination folder to create links on.
# 3+. File Extensions (optional) - A filter of file extensions to
# create links from. If this option is used, files with different
# extensions will not be used when creating symlinks.
# ----------------------------------------------------
function pring_usage
{
echo "Usage: $(basename "$0") <Source File / Directory> <Destination Directory> [<File Extensions>...]"
}
# Assure a valid amount of command-line arguments was passed
if [[ $# -lt 2 ]]; then
echo "Error: Missing parameters." >&2
pring_usage
exit 1
fi
# Assure source file / directory exists
if [[ ! -e "$1" ]]; then
echo -e "Source file / folder $1 doesn't exist."
fi
# Remove trailing '/' if it exists
source_dir=${1%/}
destination_dir=${2%/}
# Source parameter ($1) is a file
if [[ -f "$source_dir" ]]; then
ln --symbolic -- "$source_dir" "$2"
# Source parameter ($1) is a directory
elif [[ -d "$source_dir" ]]; then
# Default value - matches all filenames
regex=".*"
# If file extensions were passed
if [[ $# -gt 2 ]]; then
# Generate and replace default iregex expression
regex="$(echo ".*\(${*:3}\)$" | sed 's/ /\\|/g')"
fi
cd -- "$source_dir" || exit 1
# Generate symlinks for files in root directory
find -- * -maxdepth 0 -type f -iregex "$regex" \
-exec ln --symbolic -- "$source_dir"/{} "$destination_dir"/{} \;
# List of files matching the file extensions filter that are in subdirectories
subdir_files="$(find -- * -mindepth 1 -type f -iregex "$regex")"
# Check whether there are subdirectories
if [[ -n $subdir_files ]]; then
# Generate subdirectories
while read -r path; do
new_subdir_path="$destination_dir"/$(dirname "$path")
if [[ ! -d "$new_subdir_path" ]]; then
mkdir --parents "$new_subdir_path"
fi
done <<< "$subdir_files"
# Generate symlinks
while read -r path; do
ln --symbolic -- "$source_dir"/"$path" "$destination_dir"/"$path"
done <<< "$subdir_files"
fi
fi