一、運行 shell
#!/bin/bash
echo "hello shell"
(1) bash test.sh
(2)chmod +x test.sh;./test.sh
二、shell 變量
1. 賦值命名規則
- 首個字符必須爲字母(a-z,A-Z)
- 中間不能有空格,可以使用下劃線(_)
- 不能使用標點符號
- 不能使用bash裏的關鍵字
2. 使用變量
在變量前加 $ 符號,例如:
myint=1234
myfloat=3.24
mystr="hello"
mychar='c'
echo $myint
echo $myfloat
echo $mystr
echo $mychar
3. 操作變量
(1)只讀變量
readonly x=100
echo $x
x=200
echo $x
(2)刪除變量
x=100
echo $x
unset x
echo $x
4. 變量類型
- 本地變量: 局部變量在腳本或命令中定義,僅在當前shell實例中有效,其他shell啓動的程序不能訪問局部變量
- 環境變量: 所有的程序,包括shell啓動的程序,都能訪問環境變量,有些程序需要環境變量來保證其正 常運行。必要的時候shell腳本也可以定義環境變量,export(設置),unset(取消),env(查看)
- shell變量: shell變量是由shell程序設置的特殊變量。shell變量中有一部分是環境變量,有一部分是局部 變量,這些變量保證了shell的正常運行
三、字符串
1. 拼接
把字符串寫在一起,邊界加上{}
str1="hello"
str2=" word"
echo $str1${str2} haha
2. 字符串長度
str="shell"
echo ${#str}
3. 提取字符串
str="hello shell"
echo ${str:6:10}
4.查找字符串
str="you are great man!"
echo `expr index "$str" are`
四、文件名代換
- 通配符 * : 匹配0個或多個任意字符
- ? : 匹配一個任意字符
- [若干字符] : 匹配方括號中任意一個字符的一次出現