摘要: 如何 在shell 腳本 中 傳遞解析變量的值.
分享一個shell 中的一個小技巧, 動態改變字符串中的一些值, 通過變量的方式 傳入進去 .
舉個例子: 我希望 一個字符串可以解析一個變量 的值. 比如 num=10
num=10
string='I am ${num}'
echo $string # I am 10
一種情況 字符串 本身 用單引號.
shell 中 如何 在 單引號的字符串中傳遞變量
# test1.sh
#!/bin/bash
num=100
echo "num:${num}"
sentence='hello ,I am frank.${num}'
echo "${sentence}"
結果如下:
$ sh test1.sh
num:100
hello ,I am frank.${num}
期望 打印 num 爲100 , 但是 卻打印了原生的字符串, 如果 希望 把num 的值 解析到字符串裏面. 可以在 ${num} 添加單引號 ,注意這裏 是單引號.
# cat test.sh
num=100
echo "num:${num}"
sentence='hello ,I am frank.'${num}''
echo "sentence:${sentence}"
結果如下:
$ sh test1.sh
num:100
sentence:hello ,I am frank.100
注意 以上 sentence 變量 是 單引號的字符串, 所以要想 把變量傳入到單引號的字符串 裏面, 可以 使用 ‘’ 將變量括起來 就可以傳遞進來.
一種情況 字符串 本身 用雙引號
#!/bin/bash
num=100
echo "num:${num}"
sentence="hello ,I am frank.${num}"
echo "sentence:${sentence}"
$ sh test.sh
num:100
sentence:hello ,I am frank.100
這種 是可以正常解析的. 如果 你想 讓其顯示 是 ‘100’ 這樣的 話, 可以直接 在變量的時候 加上單引號,
#!/bin/bash
num=100
echo "num:${num}"
sentence="hello ,I am frank.'${num}'"
echo "sentence:${sentence}"
結果 如下:
$ sh test.sh
num:100
sentence:hello ,I am frank.‘100’
舉個應用場景的例子
比如 用 curl 發起一個 post 請求. 需要 在body 裏面傳入一些值, 這些值 我想通過 變量的形式傳入進去
在 body 裏面 有一個參數 是 手機號, 我想通過我生成一個變量傳入到 body 中 來改變 手機號的值 .
curl 中 參數 -d, --data DATA HTTP POST 數據
-d, --data
(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to
pass the data to the server using the content-type application/x-www-form-urlencoded.
(HTTP)將POST請求中的指定數據發送到HTTP服務器,就像用戶填寫HTML表單並按下提交按鈕時瀏覽器一樣。 這將導致curl 使用content-type application / x-www-form-urlencoded將數據傳遞到服務器。
來看一下 下面的腳本
#!/bin/bash
# test_request.sh
for i in `seq 10 200 `;do
num=$(( $i % 100 ))
curl -X POST \
http://aaaa.bbbbbbb.cn/data_service/element \
-H 'Content-Type: application/json' \
-d '{
"context": {
"id_card_number": "1312341234123412",
"mobile": "123278605'${num}'",
"name": "張三四",
"age":18,
"decision_time": "2018-10-26 10:33:09"
},
"element_id": "Frank_Test_Model_Prob"
}'
done
這裏就需要 用 ‘’ 把 ${num} 括起來,這樣才能識別num, -d 才能夠 識別這個參數.
總結
在shell 腳本中 單引號和雙引號 是有點區別的. 如果 要在字符串中傳遞 shell變量, 對於單引號的 的字符串 想要傳遞變量需要加上單引號. 而雙引號不用,直接引用變量 即可解析變量.
在 python 中, 單引號幾乎等於雙引號的,在shell 編程中這一點卻不一樣.