如何在 case 語句中使用進程替換而不會出現語法錯誤?

如何在 case 語句中使用進程替換而不會出現語法錯誤?

我在 /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/shUbuntu 系統上)不支援它,並且 bash 呼叫時/bin/sh也不支援它。

如果您有可用的 bash,請將腳本的第一行更改為,例如#!/bin/bash.

[在可安裝檔案系統的目錄中包含 bash 的系統上(例如/usr/local/bin在某些系統上),您可能需要在啟動服務之前確保檔案系統可用。 ]

答案2

工藝替代是一個巴什主義,但是你的舍邦線#!/bin/sh。除非/bin/shBash 或其他支援進程替換的 shell,否則確實不支援該語法,正如@馬克普洛特尼克

相關內容