OSDN Git Service

Regular updates
[twpd/master.git] / bash.md
1 ---
2 title: Bash scripting
3 category: CLI
4 layout: 2017/sheet
5 tags: [Featured]
6 updated: 2019-03-23
7 keywords:
8   - Variables
9   - Functions
10   - Interpolation
11   - Brace expansions
12   - Loops
13   - Conditional execution
14   - Command substitution
15 ---
16
17 Getting started
18 ---------------
19 {: .-three-column}
20
21 ### Example
22
23 ```bash
24 #!/usr/bin/env bash
25
26 NAME="John"
27 echo "Hello $NAME!"
28 ```
29
30 ### Variables
31
32 ```bash
33 NAME="John"
34 echo $NAME
35 echo "$NAME"
36 echo "${NAME}!"
37 ```
38
39 ### String quotes
40
41 ```bash
42 NAME="John"
43 echo "Hi $NAME"  #=> Hi John
44 echo 'Hi $NAME'  #=> Hi $NAME
45 ```
46
47 ### Shell execution
48
49 ```bash
50 echo "I'm in $(pwd)"
51 echo "I'm in `pwd`"
52 # Same
53 ```
54
55 See [Command substitution](http://wiki.bash-hackers.org/syntax/expansion/cmdsubst)
56
57 ### Conditional execution
58
59 ```bash
60 git commit && git push
61 git commit || echo "Commit failed"
62 ```
63
64 ### Functions
65 {: id='functions-example'}
66
67 ```bash
68 get_name() {
69   echo "John"
70 }
71
72 echo "You are $(get_name)"
73 ```
74
75 See: [Functions](#functions)
76
77 ### Conditionals
78 {: id='conditionals-example'}
79
80 ```bash
81 if [[ -z "$string" ]]; then
82   echo "String is empty"
83 elif [[ -n "$string" ]]; then
84   echo "String is not empty"
85 fi
86 ```
87
88 See: [Conditionals](#conditionals)
89
90 ### Strict mode
91
92 ```bash
93 set -euo pipefail
94 IFS=$'\n\t'
95 ```
96
97 See: [Unofficial bash strict mode](http://redsymbol.net/articles/unofficial-bash-strict-mode/)
98
99 ### Brace expansion
100
101 ```bash
102 echo {A,B}.js
103 ```
104
105 | `{A,B}` | Same as `A B` |
106 | `{A,B}.js` | Same as `A.js B.js` |
107 | `{1..5}` | Same as `1 2 3 4 5` |
108
109 See: [Brace expansion](http://wiki.bash-hackers.org/syntax/expansion/brace)
110
111
112 Parameter expansions
113 --------------------
114 {: .-three-column}
115
116 ### Basics
117
118 ```bash
119 name="John"
120 echo ${name}
121 echo ${name/J/j}    #=> "john" (substitution)
122 echo ${name:0:2}    #=> "Jo" (slicing)
123 echo ${name::2}     #=> "Jo" (slicing)
124 echo ${name::-1}    #=> "Joh" (slicing)
125 echo ${name:(-1)}   #=> "n" (slicing from right)
126 echo ${name:(-2):1} #=> "h" (slicing from right)
127 echo ${food:-Cake}  #=> $food or "Cake"
128 ```
129
130 ```bash
131 length=2
132 echo ${name:0:length}  #=> "Jo"
133 ```
134
135 See: [Parameter expansion](http://wiki.bash-hackers.org/syntax/pe)
136
137 ```bash
138 STR="/path/to/foo.cpp"
139 echo ${STR%.cpp}    # /path/to/foo
140 echo ${STR%.cpp}.o  # /path/to/foo.o
141
142 echo ${STR##*.}     # cpp (extension)
143 echo ${STR##*/}     # foo.cpp (basepath)
144
145 echo ${STR#*/}      # path/to/foo.cpp
146 echo ${STR##*/}     # foo.cpp
147
148 echo ${STR/foo/bar} # /path/to/bar.cpp
149 ```
150
151 ```bash
152 STR="Hello world"
153 echo ${STR:6:5}   # "world"
154 echo ${STR:-5:5}  # "world"
155 ```
156
157 ```bash
158 SRC="/path/to/foo.cpp"
159 BASE=${SRC##*/}   #=> "foo.cpp" (basepath)
160 DIR=${SRC%$BASE}  #=> "/path/to/" (dirpath)
161 ```
162
163 ### Substitution
164
165 | Code | Description |
166 | --- | --- |
167 | `${FOO%suffix}` | Remove suffix |
168 | `${FOO#prefix}` | Remove prefix |
169 | --- | --- |
170 | `${FOO%%suffix}` | Remove long suffix |
171 | `${FOO##prefix}` | Remove long prefix |
172 | --- | --- |
173 | `${FOO/from/to}` | Replace first match |
174 | `${FOO//from/to}` | Replace all |
175 | --- | --- |
176 | `${FOO/%from/to}` | Replace suffix |
177 | `${FOO/#from/to}` | Replace prefix |
178
179 ### Comments
180
181 ```bash
182 # Single line comment
183 ```
184
185 ```bash
186 : '
187 This is a
188 multi line
189 comment
190 '
191 ```
192
193 ### Substrings
194
195 | `${FOO:0:3}`  | Substring _(position, length)_ |
196 | `${FOO:-3:3}` | Substring from the right |
197
198 ### Length
199
200 | `${#FOO}` | Length of `$FOO` |
201
202 ### Default values
203
204 | `${FOO:-val}`        | `$FOO`, or `val` if not set |
205 | `${FOO:=val}`        | Set `$FOO` to `val` if not set |
206 | `${FOO:+val}`        | `val` if `$FOO` is set |
207 | `${FOO:?message}`    | Show error message and exit if `$FOO` is not set |
208
209 The `:` is optional (eg, `${FOO=word}` works)
210
211 Loops
212 -----
213 {: .-three-column}
214
215 ### Basic for loop
216
217 ```bash
218 for i in /etc/rc.*; do
219   echo $i
220 done
221 ```
222
223 ### C-like for loop
224
225 ```bash
226 for ((i = 0 ; i < 100 ; i++)); do
227   echo $i
228 done
229 ```
230
231 ### Ranges
232
233 ```bash
234 for i in {1..5}; do
235     echo "Welcome $i"
236 done
237 ```
238
239 #### With step size
240
241 ```bash
242 for i in {5..50..5}; do
243     echo "Welcome $i"
244 done
245 ```
246
247 ### Reading lines
248
249 ```bash
250 < file.txt | while read line; do
251   echo $line
252 done
253 ```
254
255 ### Forever
256
257 ```bash
258 while true; do
259   ยทยทยท
260 done
261 ```
262
263 Functions
264 ---------
265 {: .-three-column}
266
267 ### Defining functions
268
269 ```bash
270 myfunc() {
271     echo "hello $1"
272 }
273 ```
274
275 ```bash
276 # Same as above (alternate syntax)
277 function myfunc() {
278     echo "hello $1"
279 }
280 ```
281
282 ```bash
283 myfunc "John"
284 ```
285
286 ### Returning values
287
288 ```bash
289 myfunc() {
290     local myresult='some value'
291     echo $myresult
292 }
293 ```
294
295 ```bash
296 result="$(myfunc)"
297 ```
298
299 ### Raising errors
300
301 ```bash
302 myfunc() {
303   return 1
304 }
305 ```
306
307 ```bash
308 if myfunc; then
309   echo "success"
310 else
311   echo "failure"
312 fi
313 ```
314
315 ### Arguments
316
317 | Expression | Description                        |
318 | ---        | ---                                |
319 | `$#`       | Number of arguments                |
320 | `$*`       | All arguments                      |
321 | `$@`       | All arguments, starting from first |
322 | `$1`       | First argument                     |
323
324 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
325
326 Conditionals
327 ------------
328 {: .-three-column}
329
330 ### Conditions
331
332 Note that `[[` is actually a command/program that returns either `0` (true) or `1` (false). Any program that obeys the same logic (like all base utils, such as `grep(1)` or `ping(1)`) can be used as condition, see examples.
333
334 | Condition                | Description           |
335 | ---                      | ---                   |
336 | `[[ -z STRING ]]`        | Empty string          |
337 | `[[ -n STRING ]]`        | Not empty string      |
338 | `[[ STRING == STRING ]]` | Equal                 |
339 | `[[ STRING != STRING ]]` | Not Equal             |
340 | ---                      | ---                   |
341 | `[[ NUM -eq NUM ]]`      | Equal                 |
342 | `[[ NUM -ne NUM ]]`      | Not equal             |
343 | `[[ NUM -lt NUM ]]`      | Less than             |
344 | `[[ NUM -le NUM ]]`      | Less than or equal    |
345 | `[[ NUM -gt NUM ]]`      | Greater than          |
346 | `[[ NUM -ge NUM ]]`      | Greater than or equal |
347 | ---                      | ---                   |
348 | `[[ STRING =~ STRING ]]` | Regexp                |
349 | ---                      | ---                   |
350 | `(( NUM < NUM ))`        | Numeric conditions    |
351
352 | Condition              | Description              |
353 | ---                    | ---                      |
354 | `[[ -o noclobber ]]`   | If OPTIONNAME is enabled |
355 | ---                    | ---                      |
356 | `[[ ! EXPR ]]`         | Not                      |
357 | `[[ X ]] && [[ Y ]]`   | And                      |
358 | `[[ X ]] || [[ Y ]]`   | Or                       |
359
360 ### File conditions
361
362 | Condition               | Description             |
363 | ---                     | ---                     |
364 | `[[ -e FILE ]]`         | Exists                  |
365 | `[[ -r FILE ]]`         | Readable                |
366 | `[[ -h FILE ]]`         | Symlink                 |
367 | `[[ -d FILE ]]`         | Directory               |
368 | `[[ -w FILE ]]`         | Writable                |
369 | `[[ -s FILE ]]`         | Size is > 0 bytes       |
370 | `[[ -f FILE ]]`         | File                    |
371 | `[[ -x FILE ]]`         | Executable              |
372 | ---                     | ---                     |
373 | `[[ FILE1 -nt FILE2 ]]` | 1 is more recent than 2 |
374 | `[[ FILE1 -ot FILE2 ]]` | 2 is more recent than 1 |
375 | `[[ FILE1 -ef FILE2 ]]` | Same files              |
376
377 ### Example
378
379 ```bash
380 if ping -c 1 google.com; then
381   echo "It appears you have a working internet connection"
382 fi
383 ```` 
384
385 ```bash
386 if grep -q 'foo' ~/.bash_history; then
387   echo "You appear to have typed 'foo' in the past"
388 fi
389 ```
390
391 ```bash
392 # String
393 if [[ -z "$string" ]]; then
394   echo "String is empty"
395 elif [[ -n "$string" ]]; then
396   echo "String is not empty"
397 fi
398 ```
399
400 ```bash
401 # Combinations
402 if [[ X ]] && [[ Y ]]; then
403   ...
404 fi
405 ```
406
407 ```bash
408 # Equal
409 if [[ "$A" == "$B" ]]
410 ```
411
412 ```bash
413 # Regex
414 if [[ "A" =~ "." ]]
415 ```
416
417 ```bash
418 if (( $a < $b )); then
419    echo "$a is smaller than $b"
420 fi
421 ```
422
423 ```bash
424 if [[ -e "file.txt" ]]; then
425   echo "file exists"
426 fi
427 ```
428
429 Arrays
430 ------
431
432 ### Defining arrays
433
434 ```bash
435 Fruits=('Apple' 'Banana' 'Orange')
436 ```
437
438 ```bash
439 Fruits[0]="Apple"
440 Fruits[1]="Banana"
441 Fruits[2]="Orange"
442 ```
443
444 ### Working with arrays
445
446 ```bash
447 echo ${Fruits[0]}           # Element #0
448 echo ${Fruits[@]}           # All elements, space-separated
449 echo ${#Fruits[@]}          # Number of elements
450 echo ${#Fruits}             # String length of the 1st element
451 echo ${#Fruits[3]}          # String length of the Nth element
452 echo ${Fruits[@]:3:2}       # Range (from position 3, length 2)
453 ```
454
455 ### Operations
456
457 ```bash
458 Fruits=("${Fruits[@]}" "Watermelon")    # Push
459 Fruits+=('Watermelon')                  # Also Push
460 Fruits=( ${Fruits[@]/Ap*/} )            # Remove by regex match
461 unset Fruits[2]                         # Remove one item
462 Fruits=("${Fruits[@]}")                 # Duplicate
463 Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
464 lines=(`cat "logfile"`)                 # Read from file
465 ```
466
467 ### Iteration
468
469 ```bash
470 for i in "${arrayName[@]}"; do
471   echo $i
472 done
473 ```
474
475 Dictionaries
476 ------------
477 {: .-three-column}
478
479 ### Defining
480
481 ```bash
482 declare -A sounds
483 ```
484
485 ```bash
486 sounds[dog]="bark"
487 sounds[cow]="moo"
488 sounds[bird]="tweet"
489 sounds[wolf]="howl"
490 ```
491
492 Declares `sound` as a Dictionary object (aka associative array).
493
494 ### Working with dictionaries
495
496 ```bash
497 echo ${sounds[dog]} # Dog's sound
498 echo ${sounds[@]}   # All values
499 echo ${!sounds[@]}  # All keys
500 echo ${#sounds[@]}  # Number of elements
501 unset sounds[dog]   # Delete dog
502 ```
503
504 ### Iteration
505
506 #### Iterate over values
507
508 ```bash
509 for val in "${sounds[@]}"; do
510   echo $val
511 done
512 ```
513
514 #### Iterate over keys
515
516 ```bash
517 for key in "${!sounds[@]}"; do
518   echo $key
519 done
520 ```
521
522 Options
523 -------
524
525 ### Options
526
527 ```bash
528 set -o noclobber  # Avoid overlay files (echo "hi" > foo)
529 set -o errexit    # Used to exit upon error, avoiding cascading errors
530 set -o pipefail   # Unveils hidden failures
531 set -o nounset    # Exposes unset variables
532 ```
533
534 ### Glob options
535
536 ```bash
537 set -o nullglob    # Non-matching globs are removed  ('*.foo' => '')
538 set -o failglob    # Non-matching globs throw errors
539 set -o nocaseglob  # Case insensitive globs
540 set -o globdots    # Wildcards match dotfiles ("*.sh" => ".foo.sh")
541 set -o globstar    # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')
542 ```
543
544 Set `GLOBIGNORE` as a colon-separated list of patterns to be removed from glob
545 matches.
546
547 History
548 -------
549
550 ### Commands
551
552 | `history` | Show history |
553 | `shopt -s histverify` | Don't execute expanded result immediately |
554
555 ### Expansions
556
557 | `!$` | Expand last parameter of most recent command |
558 | `!*` | Expand all parameters of most recent command |
559 | `!-n` | Expand `n`th most recent command |
560 | `!n` | Expand `n`th command in history |
561 | `!<command>` | Expand most recent invocation of command `<command>` |
562
563 ### Operations
564
565 | `!!` | Execute last command again |         
566 | `!!:s/<FROM>/<TO>/` | Replace first occurrence of `<FROM>` to `<TO>` in most recent command |
567 | `!!:gs/<FROM>/<TO>/` | Replace all occurrences of `<FROM>` to `<TO>` in most recent command |
568 | `!$:t` | Expand only basename from last parameter of most recent command |
569 | `!$:h` | Expand only directory from last parameter of most recent command |
570
571 `!!` and `!$` can be replaced with any valid expansion.
572
573 ### Slices
574
575 | `!!:n` | Expand only `n`th token from most recent command (command is `0`; first argument is `1`) |
576 | `!^` | Expand first argument from most recent command |
577 | `!$` | Expand last token from most recent command |
578 | `!!:n-m` | Expand range of tokens from most recent command |
579 | `!!:n-$` | Expand `n`th token to last from most recent command |
580
581 `!!` can be replaced with any valid expansion i.e. `!cat`, `!-2`, `!42`, etc.
582
583
584 Miscellaneous
585 -------------
586
587 ### Numeric calculations
588
589 ```bash
590 $((a + 200))      # Add 200 to $a
591 ```
592
593 ```bash
594 $((RANDOM%=200))  # Random number 0..200
595 ```
596
597 ### Subshells
598
599 ```bash
600 (cd somedir; echo "I'm now in $PWD")
601 pwd # still in first directory
602 ```
603
604 ### Redirection
605
606 ```bash
607 python hello.py > output.txt   # stdout to (file)
608 python hello.py >> output.txt  # stdout to (file), append
609 python hello.py 2> error.log   # stderr to (file)
610 python hello.py 2>&1           # stderr to stdout
611 python hello.py 2>/dev/null    # stderr to (null)
612 python hello.py &>/dev/null    # stdout and stderr to (null)
613 ```
614
615 ```bash
616 python hello.py < foo.txt      # feed foo.txt to stdin for python
617 ```
618
619 ### Inspecting commands
620
621 ```bash
622 command -V cd
623 #=> "cd is a function/alias/whatever"
624 ```
625
626 ### Trap errors
627
628 ```bash
629 trap 'echo Error at about $LINENO' ERR
630 ```
631
632 or
633
634 ```bash
635 traperr() {
636   echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
637 }
638
639 set -o errtrace
640 trap traperr ERR
641 ```
642
643 ### Case/switch
644
645 ```bash
646 case "$1" in
647   start | up)
648     vagrant up
649     ;;
650
651   *)
652     echo "Usage: $0 {start|stop|ssh}"
653     ;;
654 esac
655 ```
656
657 ### Source relative
658
659 ```bash
660 source "${0%/*}/../share/foo.sh"
661 ```
662
663 ### printf
664
665 ```bash
666 printf "Hello %s, I'm %s" Sven Olga
667 #=> "Hello Sven, I'm Olga
668 ```
669
670 ### Directory of script
671
672 ```bash
673 DIR="${0%/*}"
674 ```
675
676 ### Getting options
677
678 ```bash
679 while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
680   -V | --version )
681     echo $version
682     exit
683     ;;
684   -s | --string )
685     shift; string=$1
686     ;;
687   -f | --flag )
688     flag=1
689     ;;
690 esac; shift; done
691 if [[ "$1" == '--' ]]; then shift; fi
692 ```
693
694 ### Heredoc
695
696 ```sh
697 cat <<END
698 hello world
699 END
700 ```
701
702 ### Reading input
703
704 ```bash
705 echo -n "Proceed? [y/n]: "
706 read ans
707 echo $ans
708 ```
709
710 ```bash
711 read -n 1 ans    # Just one character
712 ```
713
714 ### Special variables
715
716 | `$?` | Exit status of last task |
717 | `$!` | PID of last background task |
718 | `$$` | PID of shell |
719
720 See [Special parameters](http://wiki.bash-hackers.org/syntax/shellvars#special_parameters_and_shell_variables).
721
722 ### Go to previous directory
723
724 ```bash
725 pwd # /home/user/foo
726 cd bar/
727 pwd # /home/user/foo/bar
728 cd -
729 pwd # /home/user/foo
730 ```
731
732 ## Also see
733 {: .-one-column}
734
735 * [Bash-hackers wiki](http://wiki.bash-hackers.org/) _(bash-hackers.org)_
736 * [Shell vars](http://wiki.bash-hackers.org/syntax/shellvars) _(bash-hackers.org)_
737 * [Learn bash in y minutes](https://learnxinyminutes.com/docs/bash/) _(learnxinyminutes.com)_
738 * [Bash Guide](http://mywiki.wooledge.org/BashGuide) _(mywiki.wooledge.org)_
739 * [ShellCheck](https://www.shellcheck.net/) _(shellcheck.net)_