-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd-alias.zsh
executable file
·98 lines (84 loc) · 2.11 KB
/
add-alias.zsh
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
88
89
90
91
92
93
94
95
96
97
98
#!/usr/bin/zsh
function HELP {
printf "Adds or removes an alias to file ~/.aliases.
If terminal's rc file doesn't source ~/.aliases, adds a line to do so.
If no command provided, prints the current alias.
Usage: add [flags] [alias] [command]
Flags:
-d: delete given alias (terminating)
-h: print this message (terminating)
"
}
export ALIASES_FILE=$HOME/.aliases
# Init aliases file if it doesn't exist.
if [ ! -e $ALIASES_FILE ]; then
touch $ALIASES_FILE;
chmod +x $ALIASES_FILE
fi
# If no args, show help and quit.
if [ $# -eq 0 ]; then
HELP
return 0
fi
# Print current mapping for alias in aliases file.
function printAlias() {
gawk -F= -v"alias=$1" '$1 ~ "alias "alias"=" { print $0 }' $ALIASES_FILE
}
# Remove an alias from aliases file.
function deleteAlias() {
gawk -F= -v"alias=$1" '$0 !~ "alias "alias"=" { print $0 }' $ALIASES_FILE > $ALIASES_FILE.tmp
mv $ALIASES_FILE.tmp $ALIASES_FILE
}
# Get current shell rc file, creating if necessary.
# If rc file does not source aliases file, add line to do so.
MYSHELL=`ps -hp $$|awk '{print $5}'`
[[ "$MYSHELL" =~ "(\w*)$" ]] && MYSHELL=$MATCH
RC_FILE="$HOME/.${MYSHELL}rc"
if [ ! -e $RC_FILE ]; then
touch $RC_FILE
fi
if ! grep --quiet "^source $ALIASES_FILE" $RC_FILE; then
echo "" >> $RC_FILE
echo "# add custom aliases" >> $RC_FILE
echo "source $ALIASES_FILE" >> $RC_FILE
fi
# process flags
OPTIND=0 # needed for getopts to work right when .add-alias is sourced
while getopts d:h opt $argv; do
case $opt in
d)
shift
printAlias $OPTARG
[[ -n `alias $OPTARG` ]] && unalias $OPTARG
echo "Deleting alias $OPTARG."
deleteAlias $OPTARG
return 0
;;
h)
HELP
return 0
;;
\?)
HELP
return 1
;;
esac
done
ALIAS=$1
if [ -z "$ALIAS" ]; then
HELP
return 0
fi
shift
COMMAND=$argv
# read out current alias if no new command provided
if [[ -z "$COMMAND" ]]; then
printAlias $ALIAS
return 0
fi
# save new alias and sort
echo "Adding alias $ALIAS='$COMMAND'"
deleteAlias $ALIAS
echo "alias $ALIAS='$COMMAND'" >> $ALIASES_FILE
sort $ALIASES_FILE -o $ALIASES_FILE
source $ALIASES_FILE