shell cheatsheet

源自:https://devhints.io/bash
此网站的其他内容也不错,例如https://devhints.io/docker

Go to previous directory

cd -

Subshells

(cd somedir; echo "I'm now in $PWD")
pwd # still in first directory

Conditionals execution

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

Conditionals

if [ -z "$string" ]; then
    echo "empty"
elif [ -n "$string" ]; then
    echo "not empty"

Function arguments

$#  Number of arguments
$*  All arguments
$@  All arguments, starting from first
$1  First argument
}
echo "You are $(get_name)"

Function return values

get_name() {
  echo "John" # return
}
echo "You are $(get_name)"

Brace expansion

echo {a,b}.js
echo {a..z}.js

String quotes

NAME="Hohn"
echo "Hi $NAME"
echo 'Hi $NAME'

Shell execution

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

Length

${#FOO} Length of $FOO

Default values

${FOO:-val} $FOO, or val if not set
${FOO:=val} Set $FOO to val if not set
${FOO:+val} val if $FOO is set
${FOO:?message} Show error message and exit if $FOO is not set

Loops

for i in /etc/rc.*; do
  echo $i
done

Printf

printf "Hello %s, I'm %s" Sven Olga
#=> "Hello Sven, I'm Olga

Special variables

$?  Exit status of last task
$!  PID of last background task
$$  PID of shell

File conditions

[ -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

Defining arrays

Fruits=('Apple' 'Banana' 'Orange')
Fruits[0]="Apple"
Fruits[1]="Banana"
Fruits[2]="Orange"

echo ${Fruits[0]}           # Element #0
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)

for i in "${arrayName[@]}"; do
  echo $i
done
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • 想要改进这个备忘单吗?参见[贡献](#贡献)部分! 目录 [为何选择Docker](#why-docker) [先...
    iOSDevLog阅读 2,137评论 0 3
  • Docker — 云时代的程序分发方式 要说最近一年云计算业界有什么大事件?Google Compute Engi...
    ahohoho阅读 15,636评论 15 147
  • 变量 变量定义 位置参数 $@ vs $* 条件控制 注意项 [ -z "" ] 前后都有空格 [ "1" \> ...
    捕鲸小能手阅读 689评论 0 0
  • 槑小姐认识明先生是在同学聚会。 槑小姐是一位天生的宅女,不上班的日子里总是选择在家度过,看看电影,做做家务,发发呆...
    菲菲菲小菲阅读 396评论 3 1