1. 程式人生 > >shell指令碼的那點小事兒--shell初認識(一)

shell指令碼的那點小事兒--shell初認識(一)

1.第一個shell指令碼
1.1建立一個shell指令碼
touch xxx.sh
標配格式

#!/bin/bash ->這一行是標準頭部,不可以去掉
echo "hello world!"

1.2.mac終端檢視檔案

ls -l hello.sh
e.g:[email protected] 1 avalanching  staff  32  8 30 16:58 hello.sh

.mac終端修改檔案許可權
修改為可執行的

chmod +x ./hello.sh

1.4.mac終端執行Shell指令碼檔案

./hello.sh

2.shell指令碼基本語法
2.1 # ->註釋, 在shell指令碼中只有單行註釋

# 這是一行註釋

2.2 定義變數

  • 注意a:請不要新增$作為字首,$$為取值符號
  • 注意b:變數名和等號之間不能加入空格
  • 注意c:變數名字首必須是字母或下劃線
  • 注意d:變數名中間不能穿插標點符號和空格
name="smile 2017"

2.3 定義只讀變數 關鍵之readonly

name="我是隻讀的"
readonly name

2.4 刪除變數 (shell指令碼因為錯誤而停止執行)

#!/bin/bash
name="Andy"
#輸出變數
echo $name
#刪除變數
unset name
#刪除變數
echo $name
echo "執行了"

2.5基本的變數型別
a.型別一:本地變數 作用域為整個bash程序
語法:name=”Dream”
b.型別二:區域性程式碼 作用域為本地的程式碼段(修飾符local)
語法:local name=”Andy”
c.型別三:環境變數 作用域當前的shell程序以及shell的子程序(修飾符export)
語法:export name=”Andy”
d.型別四:位置變數 獲取傳入的引數

#!/bin/bash
filename=${0}
name=${1}
age=${2}
sex=${3}
echo "指令碼名稱:${filename} 姓名:${name}
年齡:${age} 性別:${sex}"

呼叫的指令:

/hello.sh Andy 190

e.型別五:特殊變數

  • ${0} -> 獲取檔案的名稱
  • ${?} -> 返回上一個命令執行的狀態的返回值

value:

  • 0:執行成功 1:執行返回的結果
  • 2:表示狀態碼(0-255)
  • $# ->引數個數
  • $* ->引數列表 所有的引數組成一個字串
  • [email protected] ->引數列表 引數單一存在
  • ${$} ->當前shell的程序ID
  • ${!} ->上一個shell的程序ID

3.Shell的字串
3.1 字串中的單引號

#!/bin/bash
name='Andy'
echo $name

3.2 字串的雙引號

#!/bin/bash
name="Andy"
echo $name

3.3字串的拼接
a)

#!/bin/bash
name='Andy'
age=100
sex="男"
info="${name}@{age}@{sex}"
echo $info

b)

#!/bin/bash
name='Andy'
age=100
sex="男"
info="姓名:"${name}" 年齡:"@{age}" 性別:"@{sex}""
echo ${info}

3.4獲取字串的長度:
語法:${#變數名稱}

#!/bin/bash
string="Andy"
echo ${#string}

3.5字串擷取
1.語法:${變數名:開始位置:擷取長度}
2.語法:

#!/bin/bash
string="I have a dream"
echo ${string:3:5}

lenght = ${#string} - 1
echo ${string:2:lenght}

echo ${string:2}

3.6 刪除字串
語法一:${變數名#要刪除的字串 正則表示式}
作用:從字串的開頭開始匹配,刪除

#!/bin/bash
string="I have a dream dd"
result=${string#I}
echo $result

result=${string#*d}
echo $result

result=${string#h*d}
echo $result

語法二:${變數名##要刪除的字串正則表示式}
作用:從字串的尾部開始匹配 往前面刪除

#!/bin/bash
string="I have a dream dd"
result=${string##I}
echo $result

result=${string##*d}
echo $result

語法三:${變數名%要刪除的字串正則表示式}
作用:從字串的尾部開始匹配,刪除

#!/bin/bash
string="I have a dream dda"
result=${string%d}
echo $result

result=${string%d*}
echo $result

語法三:${變數名%%要刪除的字串正則表示式} 查詢方向逆轉

#!/bin/bash
string="I have a dream dda"
result=${string%%d}
echo $result

result=${string%%d*}
echo $result

3.7總結
#表示從左邊往右邊刪除,查詢方向為從左邊到右邊
##表示從左邊往右邊刪除,查詢方向為從右邊到左邊

%表示從右邊往左邊刪除,查詢方向為從左邊到右邊
%%表示從右邊往左邊刪除,查詢方向為從右邊到左邊