This post is Part One of Bash Programming.
Introduction
Common shell types:
- Bourne (sh)
- Bourne-again (bash)
- C (csh)
- tcsh
- Korn (ksh)
- zsh
Check current shell:
1 | echo $0 |
Check default shell:
1 | echo $SHELL |
Check shell’s process:
1 | ps auxf | grep bash -A 2 |
Prompts:
PS1
:$
for normal user,#
for rootPS2
:>
Shell scripts always start with:
1 |
Check exit status:
1 | echo $? |
Number | Meaning |
---|---|
0 | Success |
1 | Unknown error |
126 | Command cannot be executed |
127 | Invalid command |
130 | Exit via Ctrl + c |
Variables
Variables in shell:
- All treated as chars
- Direct assignment
Definition
<var>=<char>
(Numbers, Letters, and_
)
Assignment:
1 | <var>=$(command) |
read
:
Option | Meaning |
---|---|
-s | quiet mode (no echo) |
-a | array |
-n | read char |
-p | prompt |
-t | wait time |
e.g. Input with prompt:
1 | read -p "Enter: " a |
declare
:
Option | Meaning |
---|---|
-r | read only |
-l | upper -> lower |
-u | lower -> upper |
e.g. Transform upper to lower:
1 | declare -l a=HELLO |
Delete Vars:
unset -f
: Only deletes functionunset -v
: Only deletes var.
e.g.
1 | a=hello |
Referencing
Remember the
$
sign. Otherwise, it’s not a var, but a string.
e.g. Print “Hello World”
1 | a=World |
Extension:
Again, must be DOUBLE QUOTES!
Expression | Meaning |
---|---|
${var} |
== $var |
${var:-word} |
如果 $var 的变量值为空或未赋值,则返回 word 字符串,防止变量为空值或因未定义而导致异常 |
${var:=word} |
如果 $var 的变量值为空或未赋值,则设置这个变量值为 word,并返回其值。位置变量和特殊变量不适用。基本同上一个,但该变量又额外给 $var 变量赋值了 |
${var:?word} |
如果 $var 变量值为空或未赋值,那么 word 字符串将被作为标准错误输出,否则输出变量的值。用于捕捉由于变量未定义而导致的错误,并退出程序 |
${var:+word} |
如果 $var 变量值为空或未赋值,则什么都不做,否则返回 word 字符串的值,也就是整个表达式的值为 word |
1 | # Since user2 isn't defined, return the string 002 |
1 | # Print user1's value, and assign 002 to user2 |
Special Vars
Positional:
$n
:
$0
: Current script’s name$1
: 1st parameter${10}
: 10th parameter (Use{ }
when n ≥ 10)
Other:
Var. | Meaning |
---|---|
$0 |
Current filename |
$# |
# of parameters passed to scripts / functions |
$_ |
Last parameter |
$* |
All parameters |
$? |
Get returned value |
$$ |
Current shell’s PID |
$! |
Last background process’ PID |