Skip to content

Instantly share code, notes, and snippets.

@2niuhe
Created June 2, 2019 20:26
Show Gist options
  • Save 2niuhe/890fb5fd340ea74466dfd171538ca262 to your computer and use it in GitHub Desktop.
Save 2niuhe/890fb5fd340ea74466dfd171538ca262 to your computer and use it in GitHub Desktop.
基础的bash脚本语法和技巧,备忘。参考https://devhints.io/bash

变量

#!/usr/bin/bash
NAME="John"
echo "Hello $NAME!"
NAME="John"
echo $NAME
echo "$NAME"
echo "${NAME}!"
#引用字符串
echo "Hi $NAME"  #=> Hi John
echo 'Hi $NAME'  #=> Hi $NAME

执行命令脚本

echo "I'm in $(pwd)"
echo "I'm in `pwd`"
#the same

控制命令执行顺序

git commit && git push                  #左边执行返回真,才执行右边
git commit || echo "Commit failed"      #坐标执行返回假,才执行右边 

函数

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

# 定义一个函数
myfunc() {
    echo "hello $1"
}
# Same as above (alternate syntax)
function myfunc() {
    echo "hello $1"
}
myfunc "John"

# 返回值
myfunc() {
    local myresult='some value'
    echo $myresult
}
result="$(myfunc)"

# 处理异常
myfunc() {
  return 1
}
if myfunc; then
  echo "success"
else
  echo "failure"
fi

# 参数表
$#          #Number of arguments
$*	        #All arguments
$@	        #All arguments, starting from first
$1	        #First argument

选择语句

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

循环语句

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

for ((i = 0 ; i < 100 ; i++)); do
  echo $i
done
# range
for i in {1..5}; do
    echo "Welcome $i"
done
# with step size
for i in {5..50..5}; do
    echo "Welcome $i"
done
# reading lines
< file.txt | while read line; do
  echo $line
done

# forever
while true; do
  ···
done

条件语句

shell中0为真值,非0为假 常用的条件语句如下:

[[ -z STRING ]]	Empty string
[[ -n STRING ]]	Not empty string
[[ STRING == STRING ]]	Equal
[[ STRING != STRING ]]	Not Equal
[[ 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
[[ STRING =~ STRING ]]	Regexp
(( NUM < NUM ))	Numeric conditions
[[ -o noclobber ]]	If OPTIONNAME is enabled
[[ ! EXPR ]]	Not
[[ X ]] && [[ Y ]]	And
[[ X ]] || [[ Y ]]	Or

参数扩展

正则表达式

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment