Bash-Shell速查表

  |  

摘要: 本文记录 Bash Shell 中常见的概念和操作

【对算法,数学,计算机感兴趣的同学,欢迎关注我哈,阅读更多原创文章】
我的网站:潮汐朝夕的生活实验室
我的公众号:算法题刷刷
我的知乎:潮汐朝夕
我的github:FennelDumplings
我的leetcode:FennelDumplings


参考链接: https://devhints.io/bash


基本操作

条件执行

1
2
git commit && git push
git commit || echo "commit failed"

条件控制

1
2
3
4
5
if [[ -z "$string" ]]; then
echo "String is empty"
elif [[ -n "$string" ]]; then
echo "String is not empty"
fi

字符串引号

1
2
3
str="czx"
echo "Hello ${str}" # 显示 Hello czx
echo 'Hello ${str}' # 显示 Hello ${str}

函数

1
2
3
4
5
get_name() {
echo "czx"
}

echo "My name is $(get_name)"

花括号展开

1
2
echo {A,B}.js # 显示 A.js B.js
echo {1..5}.js # 显示 1.js 2.js 3.js 4.js 5.js

shell命令

1
2
echo "I'm in $(pwd)"
echo "I'm in `pwd`"

注释

1
# 单行注释

注意多行注释中的 : 和 ‘ 中间有空格。

1
2
3
: '
多行注释
'

参数扩展

前后缀删除

1
2
3
4
${FOO%suffix} # Remove suffix
${FOO#prefix} # Remove prefix
${FOO%%suffix} # Remove long suffix
${FOO##prefix} # Remove long prefix
1
2
3
4
5
6
7
8
9
10
STR="/path/to/foo.cpp"
echo ${STR%.cpp} # /path/to/foo
echo ${STR%.cpp}.o # /path/to/foo.o
echo ${STR%/*} # /path/to

echo ${STR##*.} # cpp (extension)
echo ${STR##*/} # foo.cpp (basepath)

echo ${STR#*/} # path/to/foo.cpp
echo ${STR##*/} # foo.cpp
1
2
3
4
5
SRC="/path/to/foo.cpp"
BASE=${SRC##*/} #=> "foo.cpp" (basepath)
DIR=${SRC%$BASE} #=> "/path/to/" (dirpath)
echo ${BASE}
echo ${DIR}

替换

1
2
3
4
${FOO/from/to} # Replace first match
${FOO//from/to} # Replace all
${FOO/%from/to} # Replace suffix
${FOO/#from/to} # Replace prefix
1
2
name="John"
echo ${name/J/j} # => "john" (substitution)
1
2
STR="/path/to/foo.cpp"
echo ${STR/foo/bar} # /path/to/bar.cpp

长度

1
${#FOO} # Length of $FOO

默认值

1
2
3
4
${FOO:-val} # $FOO, or val if unset (or null)
${FOO:=val} # Set $FOO to val if unset (or null)
${FOO:+val} # val if $FOO is set (and not null)
${FOO:?message} # Show error message and exit if $FOO is unset (or null)
1
echo ${food:-Cake}  # => $food or "Cake"

子串

1
2
${FOO:0:3} # Substring (position, length)
${FOO:(-3):3} # Substring from the right
1
2
3
4
5
6
name="John"
echo ${name:0:2} # => "Jo" (slicing)
echo ${name::2} # => "Jo" (slicing)
echo ${name::-1} # => "Joh" (slicing)
echo ${name:(-1)} # => "n" (slicing from right)
echo ${name:(-2):1} # => "h" (slicing from right)
1
2
length=2
echo ${name:0:length} #=> "Jo"
1
2
3
STR="Hello world"
echo ${STR:6:5} # "world"
echo ${STR: -5:5} # "world", 注意 : 和 - 之间有空格

大小写

1
2
3
4
5
6
7
STR="HELLO WORLD!"
echo ${STR,} #=> "hELLO WORLD!" (lowercase 1st letter)
echo ${STR,,} #=> "hello world!" (all lowercase)

STR="hello world!"
echo ${STR^} #=> "Hello world!" (uppercase 1st letter)
echo ${STR^^} #=> "HELLO WORLD!" (all uppercase)

循环

基本循环

1
2
3
4
for i in /etc/rc.*; 
do
echo $i
done

读文件行

1
2
3
4
cat file.txt | while read line; 
do
echo $line
done

C 风格循环

1
2
3
4
for ((i = 0 ; i < 100 ; i++)); 
do
echo $i
done

while 循环

1
2
3
4
while true; 
do
···
done

范围循环

1
2
3
4
for i in {1..5}; 
do
echo "Welcome $i"
done
1
2
3
4
for i in {5..50..5}; 
do
echo "Welcome $i"
done

条件控制

条件

[[ 也是一个命令,也是会返回 0 (成功)或者正数(失败)。

1
2
3
4
5
[[ -z STRING ]] # Empty string
[[ -n STRING ]] # Not empty string
[[ STRING == STRING ]] # Equal
[[ STRING != STRING ]] # Not Equal
[[ STRING =~ STRING ]] # Regexp
1
2
3
4
5
6
7
[[ NUM -eq NUM ]] # Equal
[[ NUM -ne NUM ]] # Not equal
[[ NUM -lt NUM ]] # Less than
[[ NUM -le NUM ]] # Less than or equal
[[ NUM -gt NUM ]] # Greater than
[[ NUM -ge NUM ]] # Greater than or equal
(( NUM < NUM )) # Numeric conditions
1
2
3
4
5
6
7
8
# String
if [[ -z "$string" ]]; then
echo "String is empty"
elif [[ -n "$string" ]]; then
echo "String is not empty"
else
echo "This never happens"
fi
1
2
# Equal
if [[ "$A" == "$B" ]]
1
2
# Regex
if [[ "A" =~ . ]]
1
2
3
if (( $a < $b )); then
echo "$a is smaller than $b"
fi

多个条件

1
2
3
4
[[ -o noclobber ]] # If OPTIONNAME is enabled
[[ ! EXPR ]] # Not
[[ X && Y ]] # And
[[ X || Y ]] # Or
1
2
3
4
# Combinations
if [[ X && Y ]]; then
...
fi

文件条件

1
2
3
4
5
6
7
8
9
10
11
[[ -e FILE ]] # Exists
[[ -r FILE ]] # Readable
[[ -h FILE ]] # Symlink
[[ -d FILE ]] # Directory
[[ -w FILE ]] # Writable
[[ -s FILE ]] # Size is > 0 bytes
[[ -f FILE ]] # File
[[ -x FILE ]] # Executable
[[ FILE1 -nt FILE2 ]] # 1 is more recent than 2
[[ FILE1 -ot FILE2 ]] # 2 is more recent than 1
[[ FILE1 -ef FILE2 ]] # Same files
1
2
3
if [[ -e "file.txt" ]]; then
echo "file exists"
fi

数组

定义

1
2
3
4
5
Fruits=('Apple' 'Banana' 'Orange')

Fruits[0]="Apple"
Fruits[1]="Banana"
Fruits[2]="Orange"

操作

1
2
3
4
5
6
7
Fruits=("${Fruits[@]}" "Watermelon")    # Push
Fruits+=('Watermelon') # Also Push
Fruits=( ${Fruits[@]/Ap*/} ) # Remove by regex match
unset Fruits[2] # Remove one item
Fruits=("${Fruits[@]}") # Duplicate
Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
lines=(`cat "logfile"`) # Read from file

访问

1
2
3
4
5
6
7
8
echo ${Fruits[0]}           # Element #0
echo ${Fruits[-1]} # Last element
echo ${Fruits[@]} # All elements, space-separated
echo ${#Fruits[@]} # Number of elements
echo ${#Fruits} # String length of the 1st element
echo ${#Fruits[3]} # String length of the Nth element
echo ${Fruits[@]:3:2} # Range (from position 3, length 2)
echo ${!Fruits[@]} # Keys of all elements, space-separated

遍历

1
2
3
4
for i in "${arrayName[@]}"; 
do
echo $i
done

字典

定义

1
2
3
4
5
6
declare -A sounds

sounds[dog]="bark"
sounds[cow]="moo"
sounds[bird]="tweet"
sounds[wolf]="howl"

操作

1
unset sounds[dog]   # Delete dog

访问

1
2
3
4
echo ${sounds[dog]} # Dog's sound
echo ${sounds[@]} # All values
echo ${!sounds[@]} # All keys
echo ${#sounds[@]} # Number of elements

遍历

遍历键

1
2
3
4
for val in "${sounds[@]}"; 
do
echo $val
done

遍历值

1
2
3
4
for key in "${!sounds[@]}"; 
do
echo $key
done

选项

Options

1
2
3
4
set -o noclobber  # Avoid overlay files (echo "hi" > foo)
set -o errexit # Used to exit upon error, avoiding cascading errors
set -o pipefail # Unveils hidden failures
set -o nounset # Exposes unset variables

Glob Options

glob: 匹配路径名的通配符

1
2
3
4
5
shopt -s nullglob    # Non-matching globs are removed  ('*.foo' => '')
shopt -s failglob # Non-matching globs throw errors
shopt -s nocaseglob # Case insensitive globs
shopt -s dotglob # Wildcards match dotfiles ("*.sh" => ".foo.sh")
shopt -s globstar # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')

历史

基本操作

1
2
3
4
5
6
!! # Execute last command again
!!:s/<FROM>/<TO>/ # Replace first occurrence of <FROM> to <TO> in most recent command
!!:gs/<FROM>/<TO>/ # Replace all occurrences of <FROM> to <TO> in most recent command
!$:t # Expand only basename from last parameter of most recent command
!$:h # Expand only directory from last parameter of most recent command
!! and !$ can be replaced with any valid expansion.

注意: !!!$ 均可以替换为扩展操作。

扩展操作

1
2
3
4
5
!$ # Expand last parameter of most recent command
!* # Expand all parameters of most recent command
!-n # Expand nth most recent command
!n # Expand nth command in history
!<command> # Expand most recent invocation of command <command>

切片

1
2
3
4
5
!!:n # Expand only nth token from most recent command (command is 0; first argument is 1)
!^ # Expand first argument from most recent command
!$ # Expand last token from most recent command
!!:n-m # Expand range of tokens from most recent command
!!:n-$ # Expand nth token to last from most recent command

其它

数值计算

1
2
$((a + 200))      # Add 200 to $a
$(($RANDOM%200)) # Random number 0..199

查看命令

1
2
command -V cd
#=> "cd is a function/alias/whatever"

source 命令

1
source "${0%/*}/../share/foo.sh"

字符串转换

tr 命令

1
2
3
4
5
6
7
8
9
10
-c # Operations apply to characters not in the given set
-d # Delete characters
-s # Replaces repeated characters with single occurrence
-t # Truncates
[:upper:] # All upper case letters
[:lower:] # All lower case letters
[:digit:] # All digits
[:space:] # All whitespace
[:alpha:] # All letters
[:alnum:] # All letters and digits
1
2
echo "Welcome To Devhints" | tr [:lower:] [:upper:]
# WELCOME TO DEVHINTS

特殊变量

1
2
3
4
5
$? # Exit status of last task
$! # PID of last background task
$$ # PID of shell
$0 # Filename of the shell script
$_ # Last argument of the previous command

检查命令返回值

1
2
3
if ping -c 1 google.com; then
echo "It appears you have a working internet connection"
fi

检查 grep 的返回值

1
2
3
if grep -q 'foo' ~/.bash_history; then
echo "You appear to have typed 'foo' in the past"
fi

subshell

1
2
3
DIR=test
(cd $DIR; echo "I'm now in $PWD")
pwd # still in first directory

重定向

1
2
3
4
5
6
python hello.py > output.txt   # stdout to (file)
python hello.py >> output.txt # stdout to (file), append
python hello.py 2> error.log # stderr to (file)
python hello.py 2>&1 # stderr to stdout
python hello.py 2>/dev/null # stderr to (null)
python hello.py &>/dev/null # stdout and stderr to (null)
1
2
python hello.py < foo.txt      # feed foo.txt to stdin for python
diff <(ls -r) <(ls) # Compare two stdout without files

printf

1
2
3
4
5
6
7
8
printf "Hello %s, I'm %s" Sven Olga
#=> "Hello Sven, I'm Olga

printf "1 + 1 = %d" 2
#=> "1 + 1 = 2"

printf "This is how you print a float: %f" 2
#=> "This is how you print a float: 2.000000"

脚本文件所在目录

1
DIR="${0%/*}"

读取命令行输入

1
2
3
echo -n "Proceed? [y/n]: "
read ans
echo $ans

Case/Switch

1
2
3
4
5
6
7
8
case "$1" in
start | up)
vagrant up
;;
*)
echo "Usage: $0 {start|stop|ssh}"
;;
esac

获取 options

shell 命令根据不同的 option 返回不同执行的功能。例如 ls -lls -a

shell 脚本也可以设置 option。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
while [[ "$1" =~ ^- && ! "$1" == "--" ]]; 
do
case $1 in
-V | --version )
echo $version
exit
;;
-s | --string )
shift; string=$1
;;
-f | --flag )
flag=1
;;
esac;
shift;
done

if [[ "$1" == '--' ]]; then
shift;
fi

Share