簡體   English   中英

Systemd ExecStart中的Bash Brace擴展

[英]Bash Brace Expansion in Systemd ExecStart

以下測試在CentOS 7.1中進行。

/usr/lib/systemd/system/創建以下文件test.service

[Unit]
Description=Test Bash Brace Expansion
Wants=network.target
After=network.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/bash -c "a='hello world'; echo ${a}"

[Install]
WantedBy=multi-user.target

並執行systemctl daemon-reload; systemctl restart test; systemctl status test -l systemctl daemon-reload; systemctl restart test; systemctl status test -l

由於${a}沒有替換為單詞hello world ,因此沒有輸出值,直到它將echo ${a}更改為

  1. echo $a :工作
  2. echo $${a} :工作

$$表示aa bash中的進程的pid,但是為什么$$可以在ExecStart執行可能獲得hello world這個詞的技巧?

支撐與參數擴展

你正在做的不是支撐擴展,而是參數擴展 支撐擴展(例如${1..5}在雙引號內不起作用。

用兩個Bash shell解釋你的問題

參數擴展工作雙引號內,但如果替代應該發生在所謂的外殼,而不是當前的$符號需要被引用。

考慮這個例子:

a='bye world' ; /bin/bash -c "a='hello world'; echo ${a}"
bye world

與這一個:

a='bye world' ; /bin/bash -c "a='hello world'; echo \${a}"
hello world

將解決方案應用於systemd服務文件以及為什么`$$`可以工作

重要的是要記住,您的系統服務描述文件不是在Bash中執行的(如上面的示例所示),因此有一些非常相似但略有不同的規則,請參閱服務單元配置文件的文檔

你的問題是,就像上面第一個例子中的交互式Bash一樣,systemd正在嘗試擴展它在環境中沒有的${a} 正如您已經注意到的那樣, $$是您的解決方案,上面的鏈接解釋了原因:

要傳遞文字美元符號,請使用“$$”。

這允許參數擴展發生在系統調用的Bash shell中。 所以配置文件中的行應該是:

ExecStart=/bin/bash -c "a='hello world'; echo $${a}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM