-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheachdir.sh
More file actions
executable file
·80 lines (64 loc) · 2.09 KB
/
Copy patheachdir.sh
File metadata and controls
executable file
·80 lines (64 loc) · 2.09 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
#!/usr/bin/env bash
function _eachdir() {
if [[ ! "$1" || "$1" == "-h" || "$1" == "--help" ]]; then cat <<HELP
Run one or more commands in one or more dirs.
Usage
$ eachdir [dirs --] <commands>
By default, all subdirs of the current dir will be iterated.
Use '--' to separate a list of dirs from commands to be executed.
Multiple commands must be specified as a single string argument.
Example
# Print the working directory
$ eachdir pwd
$ eachdir * -- pwd
# Perform a 'git pull' inside for subdirs starting with 'repo-'
$ eachdir repo-* -- git pull
# Perform a few commands inside all subdirs starting with 'repo-'
$ eachdir repo-* -- 'git fetch && git merge'
HELP
return; fi
# For underlining headers.
local underline
local _underline
underline="$(tput smul)"
_underline="$(tput rmul)"
# Store any dirs passed before -- in an array.
local dashes d
local dirs=()
for d in "$@"; do
if [[ "$d" == "--" ]]; then
dashes=1
shift $(( ${#dirs[@]} + 1 ))
break
fi
dirs=("${dirs[@]}" "$d")
done
# If -- wasn't specified, default to all subdirs of the current dir.
[[ "$dashes" ]] || dirs=(*/)
local nops=()
# Do stuff for each specified dir, in each dir. Non-dirs are ignored.
for d in "${dirs[@]}"; do
# Skip non-dirs.
[[ ! -d "$d" ]] && continue
# If the dir isn't /, strip the trailing /.
[[ "$d" != "/" ]] && d="${d%/}"
# Execute the command, grabbing all stdout and stderr.
output="$( (cd "$d"; eval "$@") 2>&1 )"
if [[ "$output" ]]; then
# If the command had output, display a header and that output.
echo -e "${underline}${d}${_underline}\n$output\n"
else
# Otherwise push it onto an array for later display.
nops=("${nops[@]}" "$d")
fi
done
# List any dirs that had no output.
if [[ ${#nops[@]} -gt 0 ]]; then
echo "${underline}no output from${_underline}"
for d in "${nops[@]}"; do echo "$d"; done
fi
}
# By putting the above code inside a function, if this file is sourced (which
# is required for external aliases/functions to be used as commands), vars
# can be local and return can be used to exit.
_eachdir "$@"