字符串是shell編程中最經常使用最有用的數據類型(除了數字和字符串,也沒啥其它類型好用了),字符串能夠用單引號,也能夠用雙引號,也能夠不用引號。單雙引號的區別跟PHP相似。shell
str='this is a string'
your_name='runoob' str="Hello, I know you are \"$your_name\"! \n" echo -e $str # 輸出結果爲: # Hello, I know you are "runoob"!
your_name="runoob" # 使用雙引號拼接 greeting="hello, "$your_name" !" greeting_1="hello, ${your_name} !" echo $greeting $greeting_1 # 使用單引號拼接 greeting_2='hello, '$your_name' !' greeting_3='hello, ${your_name} !' echo $greeting_2 $greeting_3 #輸出結果爲: #hello, runoob ! hello, runoob ! #hello, runoob ! hello, ${your_name} !
string="abcd" echo ${#string} #輸出 4
如下實例從字符串第 2 個字符開始截取 4 個字符:編程
string="runoob is a great site" echo ${string:1:4} # 輸出 unoo
查找字符 i 或 o 的位置(哪一個字母先出現就計算哪一個):this
string="runoob is a great site" echo `expr index "$string" io` # 輸出 4 注意: 以上腳本中 ` 是反引號,而不是單引號 ',不要看錯了哦。