简体   繁体   English

使用incron和bash脚本调用REST API?

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

I'm using incron to check if XML files are uploaded in a folder Depot using : 我正在使用incron来检查XML文件是否通过以下方式上传到Depot文件夹中:

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

When a new file is detected, the following bash script add.sh (which is in the Depot folder) is called : 检测到新文件时,将调用以下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

The $1 var contains the name of the file, and the $fileContent var contains the XML content of the file. $1变量包含文件名,而$fileContent包含文件的XML内容。

The thing is, when I manually call the bash script from the command line (when there's already a XML file in the Depot folder) using : 问题是,当我使用以下命令从命令行手动调用bash脚本时(当Depot文件夹中已经有XML文件时):

./add.sh test.xml

everything works fine. 一切正常。 But when I try to trigger the script by dropping a new XML file into the folder, it doesn't do anything, despite showing-up in the log, tail /var/log/syslog command giving the following result : 但是,当我尝试通过将新的XML文件放入文件夹来触发脚本时,尽管在log tail /var/log/syslog命令,但它却无能为力,它给出了以下结果:

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

The only way I could get it working (by dropping a file in the folder) is when the content var is already set in the script, like so : 我可以使它工作的唯一方法(通过将文件拖放到文件夹中)是在脚本中已经设置了内容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

Am I missing something here ? 我在这里想念什么吗? Should I use another method than cat to retrieve the XML content ? 是否应该使用cat以外的其他方法来检索XML内容?

I managed to make it work ! 我设法做到了!

I changed the incron command to : 我将incron命令更改为:

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

and the bash script to : 和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

I needed to send the full path of the file to the bash script (using $@/$#) for the cat function to work properly. 我需要将文件的完整路径发送到bash脚本(使用$ @ / $#),以便cat函数正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM