-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathchdirx
More file actions
executable file
·87 lines (75 loc) · 1.92 KB
/
chdirx
File metadata and controls
executable file
·87 lines (75 loc) · 1.92 KB
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
83
84
85
86
87
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_NAME=$(basename "$0")
RECURSIVE=false
TARGET_DIR=""
usage() {
cat <<EOF
Usage: $SCRIPT_NAME [OPTIONS] <directory>
Adds executable permission to scripts in the specified directory. If a file starts with
a shebang (#!), it will be made executable.
Arguments:
<directory> The directory to process.
Options:
-r Recursively process subdirectories, including hidden ones.
-h, --help Show this help message and exit.
Examples:
$SCRIPT_NAME mydir
$SCRIPT_NAME -r mydir # Process subdirectories as well
$SCRIPT_NAME mydir -r
EOF
exit "$1"
}
# Parse arguments manually to allow flexible order
while [[ $# -gt 0 ]]; do
case "$1" in
-h | --help)
usage 0
;;
-r)
RECURSIVE=true
;;
-*)
echo "Error: Unknown option '$1'" >&2
usage 1
;;
*)
if [[ -n $TARGET_DIR ]]; then
echo "Error: Multiple directories specified: '$TARGET_DIR' and '$1'" >&2
usage 1
fi
TARGET_DIR="$1"
;;
esac
shift
done
# Ensure exactly one directory is provided
if [[ -z $TARGET_DIR ]]; then
echo "Error: No directory specified." >&2
usage 1
fi
if [[ ! -d $TARGET_DIR ]]; then
echo "Error: '$TARGET_DIR' is not a directory." >&2
exit 1
fi
process_directory() {
local dir="$1"
# Iterate over both normal and hidden files/directories
for file in "$dir"/.* "$dir"/*; do
# Skip if file doesn't exist (handles empty dirs) or if it's `.` or `..`
[[ -e $file && $file != "$dir/." && $file != "$dir/.." ]] || continue
# Skip symlinks to prevent loops and operating outside target tree
[[ -L $file ]] && continue
if [[ -f $file ]]; then
# Check if the first line starts with #!
if head -n 1 "$file" | grep -q '^#!'; then
chmod +x "$file"
echo "Added executable permission to: $file"
fi
elif [[ -d $file && $RECURSIVE == true ]]; then
# Recursively process subdirectories
process_directory "$file"
fi
done
}
process_directory "$TARGET_DIR"