-
Notifications
You must be signed in to change notification settings - Fork 0
/
.bash_utils
66 lines (52 loc) · 1.51 KB
/
.bash_utils
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
#!/usr/bin/env bash
# Utils sourced before anything else.
self="$HOME/.bash_utils"
echo Sourcing "$self"
function vsource {
# Verbose source of path if it exists.
# Usage: vsource <PATH> <FROM>
# Example: vsource ~/.bashrc "here"
arg_path=$1
arg_from=$2 ; arg_from=${arg_from:=$("pwd")} # Set default parameter if missing.
# shellcheck disable=SC1090
[ -f "$arg_path" ] && echo "Sourcing $arg_path" && source "$arg_path"
}
function prepend_path {
# Prepends some path to PATH, but prevents duplicates.
arg_path=$1 # some path
[ "${PATH#*"$arg_path":}" == "$PATH" ] && export PATH="$arg_path:$PATH"
}
function random-success {
# Successful 1 in n times.
n="$1"
local random_number=$((RANDOM % n + 1)) # Generate a random number between 1 and n.
[ "$random_number" -eq 1 ] && return 0 # Check if the random number is 1.
return 1
}
function is_yes {
ans=$(echo "$1" | tr "[:upper:]" "[:lower:]") # To lowercase.
[ "$ans" = "y" ] || [ "$ans" = "yes" ]
return $?
}
################################
# Colored echo
################################
export COLOR_RESET="\033[0m"
export COLOR_RED="\033[31m"
export COLOR_GREEN="\033[32m"
export COLOR_CYAN="\033[36m"
function echo-color() {
color="$1"
shift # Shift all args to the left.
msg="$*" # Capture all other args.
echo -e "$color""$msg""$COLOR_RESET"
}
function echo-red() {
echo-color "$COLOR_RED" "$@"
}
function echo-green() {
echo-color "$COLOR_GREEN" "$@"
}
function echo-cyan() {
echo-color "$COLOR_CYAN" "$@"
}