about summary refs log tree commit diff stats
path: root/bash/functions.bash
blob: c5bcddb2127a3fc072015f991ae38335a58fad8a (plain)
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
# Functions

memq() { # memq ITEM ARRAY
	## Test whether an ITEM is a member of ARRAY.
	## Pass ARRAY as ${ARRAY[@]}.
	local e needle="$1"
	shift
	for e; do
		[[ "$e" == "$needle" ]] && {
			return 0
		}
	done
	return 1
}

rebashrc() { # rebashrc
	## Reload ~/.bashrc
	printf "Loading ~/.bashrc..." >&2
	if source "$HOME/.bashrc"; then
		echo "OK." >&2
	else
		echo "ERROR!" >&2
	fi
}

first_which() { # first_which COMMAND...
	## Return the fully-qualified path of the first COMMAND found in $PATH.
	while :; do
		command -v "$1" && break
		[ -z "$1" ] && return 1
		shift
	done
}

please() { # please [COMMAND...]
	# if run without arguments, run the last command with 'sudo' (aka sudo !!)
	# if run WITH arguments, alias as sudo
	history -d -1
	if [ -z "$1" ]; then
		#set --	$(HISTTIMEFORMAT=$'\t' history 2 | sed 's/^.*\t//;q')
		set -- $(fc -lnr | sed 1q)
	fi
	echo >&2 sudo "$@"
	history -s sudo "$@"
	"${DEBUG:-false}" || sudo "$@"
}

mkcd() {
	if [ $# -lt 1 ]; then
		command cd
		return
	fi
	if ! [ -d "$1" ]; then
		read -p "$1 doesn't exist.  Create (Y/n)? " yn
		case "$yn" in
		n* | N*) return 1 ;;
		*) mkdir -p "$1" ;;
		esac
	fi
	command cd "$1"
}
alias cd='mkcd '