-
Notifications
You must be signed in to change notification settings - Fork 3
/
bash.txt
315 lines (253 loc) · 9.02 KB
/
bash.txt
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# Useful bash options for debugging: https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
# -u: treat unset variables as an error and exit immediately
set -euxo pipefail
# Without printing each command and expanded variables
set -euo pipefail
# Shebang for bash
# https://stackoverflow.com/questions/21612980/why-is-usr-bin-env-bash-superior-to-bin-bash
#!/usr/bin/env bash
# Loop with step
for i in {0..10..2}
do
..
done
# Loop over list of items
for file in file1 file2 file3
do
echo $file
done
# Loop over multipe lines of strings
while read line
do
echo $line
done <<EOF
line1
line2
EOF
# Looping through all lines in a file
# http://stackoverflow.com/questions/1521462/looping-through-the-content-of-a-file-in-bash
while read p; do
echo $p
done < FILEPATH.txt
# Single line
while read p; do echo $p; done <users.txt
# Process all files with certain extension
# https://stackoverflow.com/questions/14505047/loop-through-all-the-files-with-a-specific-extension
for f in *.rar; do unar "$f"; done
# Pad zero in string
n=1
wget http://aolradio.podcast.aol.com/sn/SN-`printf %03d $n`.mp3
# Run command or get env var
${HOME}
$(echo foo)
# Make output bold
# https://stackoverflow.com/questions/2924697/how-does-one-output-bold-text-in-bash
bold=$(tput bold)
normal=$(tput sgr0)
# Change output color of echo: https://stackoverflow.com/a/58149187
# Using ANSI escape sequences
Red 0;31 Light Red 1;31
Green 0;32 Light Green 1;32
Brown/Orange 0;33 Yellow 1;33
Blue 0;34 Light Blue 1;34
Purple 0;35 Light Purple 1;35
CYAN='\e[36m'
DEFAULT='\e[39m'
# Prefix with '1;' and '0;' for bold and no bold
GREEN='\e[1;32m'
DEFAULT='\e[0;39m'
printf "I ${GREEN}love${DEFAULT} Stack Overflow\n"
# Example wrapping set and unset color for easier readibility
echo -en "\e[1;32m"
echo "I am a green text"
echo -en "\e[39m"
# Using echo need this option -e: enable interpretation of backslash escapes
echo -e "I ${CYAN}love${DEFAULT} Stack Overflow"
# When printing in Java or Golang codes, usually this format is better
# Replace '\e' with '\033': CYAN='\033[36m' RED='\033[31m' RESET='\033[39m'
#
# System.out.println("I have \033[1;35m color \033[0;39m and then no color");
# Color and bold
# May also need to set TERM=xterm-color for non-interactive terminal
COLOR="\033[1;32m"
NO_COLOR="\033[0m"
echo -e "${COLOR}I'm colourful and bold${NO_COLOR}I'm normal"
# Another color example
COLOR_OK="\033[1;32m"
COLOR_ERR="\033[1;31m"
COLOR_RESET="\033[0m"
# Brace expansion
# http://unix.stackexchange.com/questions/315963/bash-command-to-copy-before-cursor-and-paste-after
echo a{b,c,d{e,f,g}}
ab ac ade adf adg
# Good reference for bash operators e.g. -z -n
# http://tldp.org/LDP/abs/html/comparison-ops.html
# https://unix.stackexchange.com/a/109631
#
# -n: string is not null
# -z: string is null, that is, has zero length
#
$ foo="bar";
$ [ -n "$foo" ] && echo "foo is not null"
foo is not null
$ [ -z "$foo" ] && echo "foo is null"
$ foo="";
$ [ -n "$foo" ] && echo "foo is not null"
$ [ -z "$foo" ] && echo "foo is null"
foo is null
# Check if variable is set
# https://stackoverflow.com/questions/3601515/how-to-check-if-a-variable-is-set-in-bash
if [[ $var ]]; then echo "var is set"; fi
# Check if variable is not set
if [[ ! $var ]]; then echo "var is not set"; fi
# Check variable equals value
if [ "$1" == "something" ]; then
# Check if variable is true: https://stackoverflow.com/a/2953673
if [ $myvar = true ]; then
echo "myvar is true"
fi
# Set variable if not set
# https://unix.stackexchange.com/questions/122845/using-a-b-for-variable-assignment-in-scripts
VAR1="${VAR1:-default value}"
VAR1="${VAR1:-$VAR2}"
# Pass literal tab character with $'\t'
sort -t $'\t'
# Get exit code of last command
echo $?
# Check if exit code is 0
# "==" for string comparison, "-eq" or "-ne" for numeric comparison
if [[ $? -ne 0 ]]; then echo "exit code not 0"; fi
# Get basename i.e. folder name without full path
basename $PWD
# Bash shortcuts
# https://gist.github.com/tuxfight3r/60051ac67c5f0445efee
ctrl + a Goto BEGINNING of command line
ctrl + e Goto END of command line
alt + f move cursor FORWARD one word
alt + b move cursor BACK one word
ctrl + w delete the word BEFORE the cursor
ctrl + u Clear all BEFORE cursor
ctrl + k Clear all AFTER cursor
!! Run PREVIOUS command (e.g. sudo !!)
alt + . print the LAST ARGUMENT
# Reset shell
reset
# Math expression: wrap in $(( ))
# https://unix.stackexchange.com/questions/40786/how-to-do-integer-float-calculations-in-bash-or-other-languages-frameworks
echo "$((20+5))"
# Check no of arguments passed
# https://stackoverflow.com/questions/18568706/check-number-of-arguments-passed-to-a-bash-script
if [[ $# -ne 1 ]]; then
echo "Illegal number of parameters"
fi
# Parse command line arguments
# https://github.com/mattbryson/bash-arg-parse/blob/master/arg_parse_example
# https://github.com/kubeflow/pipelines/blob/8e53eb43adec9dd7593f99baae24813cc40bb302/test/postsubmit-tests-with-pipeline-deployment.sh
============================================================
# positional args
args=()
# named args
while [ "$1" != "" ]; do
case "$1" in
-a | --an_arg ) an_arg="$2"; shift;;
-s | --some_more_args ) some_more_args="$2"; shift;;
-y | --yet_more_args ) yet_more_args="$2"; shift;;
-h | --help ) usage; exit;; # quit and show usage
* ) args+=("$1") # if no match, add it to the positional args
esac
shift # move to next kv pair
done
# restore positional args
set -- "${args[@]}"
# set positionals to vars
positional_1="${args[0]}"
positional_2="${args[1]}"
============================================================
# Parse command line arguments: named args ONLY without positional args
============================================================
usage()
{
echo "usage: run.sh
[-a | --an_args some arguments ]
[-s | --some_more_args some other arguments ]
[-h help]"
}
while [ "$1" != "" ]; do
case "$1" in
-a | --an_arg ) an_arg="$2"; shift;;
-s | --some_more_args ) some_more_args="$2"; shift;;
-y | --yet_more_args ) yet_more_args="$2"; shift;;
-h | --help ) usage; exit;; # quit and show usage
* ) usage; exit 1
esac
shift # move to next kv pair
done
============================================================
# Example function
print_something () {
echo Hello I am a function
}
# Multiline echo, output
# https://stackoverflow.com/questions/10969953/how-to-output-a-multiline-string-in-bash
cat << EOF
usage: up [--level <n>| -n <levels>][--help][--version]
Report bugs to:
up home page:
EOF
# Check if variable is NOT set
# https://stackoverflow.com/questions/11362250/in-bash-how-do-i-test-if-a-variable-is-defined-in-u-mode
if [ -z $MYVAR ]; then
echo MYVAR is not set
else
echo MYVAR=$MYVAR
fi
# Check if variable IS set
if [ $MYVAR ]; then
echo MYVAR=$MYVAR
else
echo MYVAR is not set
fi
# https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html#The-Set-Builtin
# Expand variables in bash script
set -x
# Exit immediately if pipeline fails
set -e
# Normally used for debuggin
set -ex
# Pass all arguments to a bash script
# https://unix.stackexchange.com/questions/78470/pass-arguments-to-function-exactly-as-is
"$@"
# e.g. use in Dockerfile
# exec "$@"
# Export environment variables set in a file containing lines of KEY=VALUE
set -o allexport # OR: set -a
source envfile
# Go to previous directory. This value is also stored in $OLDPWD
# https://superuser.com/a/113220
cd -
# Get the directory of a Bash script
# https://stackoverflow.com/questions/59895/get-the-source-directory-of-a-bash-script-from-within-the-script-itself
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
# Shorter alternative
dirname "$BASH_SOURCE"
# Get the exit code of the last (rightmost) command to exit with a non-zero status when using pipe
# https://stackoverflow.com/questions/6871859/piping-command-output-to-tee-but-also-save-exit-code-of-command
set -o pipefail
# Example:
false | tee /dev/null ; echo $?
0
set -o pipefail
false | tee /dev/null ; echo $?
1
# What does -x means in conditional
# if [ -x /etc/rc.local ] then
https://askubuntu.com/questions/445469/what-does-x-mean-in-if-conditional-statement
# Math calculation in float with bc
# https://unix.stackexchange.com/a/40787
echo 20+5/2 | bc
# Skip first 2 lines
# https://stackoverflow.com/a/604871
tail -n +3 <filename>
# Use curly braces to create multiple related files, from Addy Osmani Twitter
touch image-{header,footer}.txt
touch product.{js,css}