shell 脚本笔记

shell 解释器

shell作为脚本语言,它的解释器主要有

  • bash
    linux 默认的shell解释器,方向键查历史命令,tap补齐,help,BourneAgain Shell

  • sh
    unix标准默认的shell,Bourne Shell

  • 其他
    非主流的ash,csh,ksh

指定解释器

#!/bin/bash

变量

name="小明" #变量和等号之间不可以有空格,定义时无$符,使用时才有
echo $name
readonly id="1" #只读变量
echo ${id}
unset name #删除非只读的变量

命令替换

USER=`who|wc -l` # 反引号表示命令替换
echo "i am $USER"

read

从stdin或者文件读数据,付给变量

echo "What's your name?"
read NAME
echo "Hello,$NAME"

循环读文件

  • while
while read -r line
do
    echo $line
done < email.txt
  • for
for line in `cat email.txt`
do
    echo $line
done

while:将每行的内容读入到line变量
for:将读入的内容以IFS字段分隔符为界,逐一读入变量line。以空格区分读的字段

// while
Hello Alice
Hello bob
Hello cindy

//for
Hello
Alice
Hello
bob
Hello
cindy

curl

  • get
parse_json(){
echo "${1//\"/}" | sed "s/.*$2:\([^,}]*\).*/\1/"
}

result=$( curl http://127.0.0.1:8080/account?info&name=123)

email=$(parse_json result "name")
echo $email
  • post
postUrl="http://haha.test.com/acount/create"
cookie="a_tk=12445rt94njfksdgnflbgr13"

id=5
curl -s POST -H "content-Type:application/json" -b $cookie_info -d '{"name":"qingqing","id":"'$id'"}' $postUrl
  • cookie
curl -b cookies1.txt -c cookies.txt $url
  • 重要参数
    curl 可以直接访问HTTPS
-H, --header LINE   要发送到服务端的自定义请求头 (H)
-I, --head          仅显示响应文档头
-o, --output FILE   将输出写入文件,而非 stdout
-X, --request COMMAND  使用指定的请求命令
-v, --verbose       显示详细操作信息
-d, --data DATA     HTTP POST 数据 (H)
-s,                 只展示body

if

  • if / if…else
a=10
b=20

if [ $a == $b ]
then
   echo "a is equal to b"
fi

if [ $a == $b ]
then
   echo "a is equal to b"
else
   echo "a is not equal to b"
fi
  • if…elif…
a=10
b=20

if [ $a == $b ]
then
   echo "a is equal to b"
elif [ $a -gt $b ]
then
   echo "a is greater than b"
elif [ $a -lt $b ]
then
   echo "a is less than b"
else
   echo "None of the condition met"
fi
  • 写成一行

以命令形式运行,test表示判断某个条件是否成立 跟 [] 类似

if test $[2*3] -eq $[1+5]; then echo 'The two numbers are equal!'; fi;

符号

-gt # > greater than
-lt # < less than

你可能感兴趣的:(shell)