Merikanto

一簫一劍平生意,負盡狂名十五年

Bash Programming - 01 Vars, Exps

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 root
  • PS2: >

Shell scripts always start with:

1
#!/bin/bash

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
2
3
4
<var>=$(command)

# e.g.
a=$(echo hello)

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
2
declare -l a=HELLO
echo $a

Delete Vars:

  • unset -f: Only deletes function
  • unset -v: Only deletes var.

e.g.

1
2
a=hello
unset a

Referencing

Remember the $ sign. Otherwise, it’s not a var, but a string.

e.g. Print “Hello World”

1
2
3
a=World
b="Hello $a" # Must use DOUBLE QUOTES!
echo $b

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
2
# Since user2 isn't defined, return the string 002
echo $user1 ${user2:-002}
1
2
# Print user1's value, and assign 002 to user2
echo $user1 ${user2:=002}

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