刘毅同学

About Python, MySQL & Life

Bash Tips

| Comments

Bash 遇到错误就退出

http://stackoverflow.com/a/4382179

set -e

If you put set -e in a script, the script will terminate as soon as any command inside it fails (i.e. as soon as any command returns a nonzero status). This doesn’t let you write your own message, but often the failing command’s own messages are enough.

The advantage of this approach is that it’s automatic: you don’t run the risk of forgetting to deal with an error case.

Commands whose status is tested by a conditional (such as if, && or ||) do not terminate the script (otherwise the conditional would be pointless). An idiom for the occasional command whose failure doesn’t matter is command-that-may-fail || true. You can also turn set -e off for a part of the script with set +e.

Bash使用数组

快速入门

(Bash For Loop Array: Iterate Through Array Values)[http://www.cyberciti.biz/faq/bash-for-loop-array/]

  • 用括号指定,空格指定就好
  • 遍历: for i in "${var[@]}"

深入

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
#!/bin/bash
# array-ops.sh: More fun with arrays.


array=( zero one two three four five )
# Element 0   1   2    3     4    5

echo ${array[0]}       #  zero
echo ${array:0}        #  zero
                       #  Parameter expansion of first element,
                       #+ starting at position # 0 (1st character).
echo ${array:1}        #  ero
                       #  Parameter expansion of first element,
                       #+ starting at position # 1 (2nd character).

echo "--------------"

echo ${#array[0]}      #  4
                       #  Length of first element of array.
echo ${#array}         #  4
                       #  Length of first element of array.
                       #  (Alternate notation)

echo ${#array[1]}      #  3
                       #  Length of second element of array.
                       #  Arrays in Bash have zero-based indexing.

echo ${#array[*]}      #  6
                       #  Number of elements in array.
echo ${#array[@]}      #  6
                       #  Number of elements in array.

echo "--------------"

array2=( [0]="first element" [1]="second element" [3]="fourth element" )
#            ^     ^       ^     ^      ^       ^     ^      ^       ^
# Quoting permits embedding whitespace within individual array elements.

echo ${array2[0]}      # first element
echo ${array2[1]}      # second element
echo ${array2[2]}      #
                       # Skipped in initialization, and therefore null.
echo ${array2[3]}      # fourth element
echo ${#array2[0]}     # 13    (length of first element)
echo ${#array2[*]}     # 3     (number of elements in array)

exit

(Arrays)[http://www.tldp.org/LDP/abs/html/arrays.html]

Comments