繁体   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