簡體   English   中英

使用incron和bash腳本調用REST API?

[英]Call a REST API using incron and bash script?

我正在使用incron來檢查XML文件是否通過以下方式上傳到Depot文件夾中:

/home/parallels/Desktop/Depot IN_CLOSE_WRITE /home/parallels/Desktop/Depot/add.sh $#

檢測到新文件時,將調用以下bash腳本add.sh (位於Depot文件夾中):

#!/bin/bash
fileContent="$(cat $1)"

curl \
--header "Content-type: application/json" \
--request POST \
--data '{
    "user": "user@mail.com",
    "fileName": "'"$1"'",
    "content": "'"$fileContent"'"
}' \
http://url/of/the/api

$1變量包含文件名,而$fileContent包含文件的XML內容。

問題是,當我使用以下命令從命令行手動調用bash腳本時(當Depot文件夾中已經有XML文件時):

./add.sh test.xml

一切正常。 但是,當我嘗試通過將新的XML文件放入文件夾來觸發腳本時,盡管在log tail /var/log/syslog命令,但它卻無能為力,它給出了以下結果:

(parallels) CMD (/home/parallels/Desktop/Depot/add.sh test.xml)

我可以使它工作的唯一方法(通過將文件拖放到文件夾中)是在腳本中已經設置了內容var時,如下所示:

#!/bin/bash
fileContent="$(cat $1)" <=== Not used anymore in this case

curl \
--header "Content-type: application/json" \
--request POST \
--data '{
    "user": "user@mail.com",
    "fileName": "'"$1"'",
    "content": "
        <node>
            <subnode>
                content
            </subnode>
        </node>
"
}' \
http://url/of/the/api

我在這里想念什么嗎? 是否應該使用cat以外的其他方法來檢索XML內容?

我設法做到了!

我將incron命令更改為:

/home/parallels/Desktop/Depot IN_CLOSE_WRITE /home/parallels/Desktop/Depot/add.sh #@/$#

和bash腳本到:

#!/bin/bash
fileContent=`cat $1`
fileName=$(basename $1)

curl \
--header "Content-type: application/json" \
--request POST \
--data '
    {
        "user": "user@mail.com",
        "filename": "'"$fileName"'",
        "content": "'"$fileContent"'"
    }' \
http://url/of/the/api

我需要將文件的完整路徑發送到bash腳本(使用$ @ / $#),以便cat函數正常工作。

暫無
暫無

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

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