![如何在 case 語句中使用進程替換而不會出現語法錯誤?](https://rvso.com/image/35999/%E5%A6%82%E4%BD%95%E5%9C%A8%20case%20%E8%AA%9E%E5%8F%A5%E4%B8%AD%E4%BD%BF%E7%94%A8%E9%80%B2%E7%A8%8B%E6%9B%BF%E6%8F%9B%E8%80%8C%E4%B8%8D%E6%9C%83%E5%87%BA%E7%8F%BE%E8%AA%9E%E6%B3%95%E9%8C%AF%E8%AA%A4%EF%BC%9F.png)
我在 /etc/init.d/myfile 中有一個作為服務載入的腳本
當我嘗試啟動服務時出現錯誤
/etc/init.d/myservice: 21: /etc/init.d/myservice: Syntax error: "(" unexpected
問題似乎與來源命令中的進程替換 <( 有關。我在其他腳本中使用它從我的主配置檔案中提取變數沒有任何問題,但在 case 語句中我不知道如何使其工作。
我的服務包含:
#!/bin/sh
#/etc/init.d/myservice
### BEGIN INIT INFO
# Provides: myservice
# Required-Start: $remote_fs $syslog $network
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: my service
# Description: Start the myservice service
### END INIT INFO
case "$1" in
start)
# start processes
# Import the following variables from config.conf: cfgfile, dir, bindir
source <(grep myservice /opt/mysoftware/config.conf | grep -oP '.*(?= #)')
if [ -f $cfgfile ]
then
echo "Starting myservice"
/usr/bin/screen -U -d -m $bindir/myscript.sh $cfgfile
else
echo "myservice could not start because the file $cfgfile is missing"
fi
;;
stop)
# kill processes
echo "Stopping myservice"
screen -ls | grep Detached | cut -d. -f1 | awk '{print $1}' | xargs kill
;;
restart)
# kill and restart processes
/etc/init.d/myservice stop
/etc/init.d/myservice start
;;
*)
echo "Usage: /etc/init.d/myservice {start|stop|restart}"
exit 1
;;
esac
exit 0
檔案 config.conf 是變數聲明的列表,其中包含簡短描述以及使用它們的腳本名稱。我使用 grep 過濾器僅獲取給定腳本所需的變數。
它看起來像這樣:
var1=value # path to tmp folder myservice
var2=value # log file name myservice script1.sh script2.sh
var3=value # prefix for log file script1.sh script2.sh
注意:在我將其轉換為開始使用設定檔而不是硬編碼值之前,該服務運作良好。
謝謝。
答案1
Bash、ksh93、zsh 和其他最新的 shell 支援進程替換(<(command)
語法),但它是非標準擴充。 Dash(在/bin/sh
Ubuntu 系統上)不支援它,並且 bash 呼叫時/bin/sh
也不支援它。
如果您有可用的 bash,請將腳本的第一行更改為,例如#!/bin/bash
.
[在可安裝檔案系統的目錄中包含 bash 的系統上(例如/usr/local/bin
在某些系統上),您可能需要在啟動服務之前確保檔案系統可用。 ]