3

I have a script which using a curl command to send a request to a web service, the output of the web service is written to a file. The file is then moved to another location.

Instead of using a delay in the script (to wait for the completion of writing the output to a file) is there any way to identify whether the curl command has finished successfully and the output has been written to a file?

I want to avoid a scenario when I'm moving the file while information is still being written to it.

Appreciate your input

1
  • Why would you even think of using a delay?  Are you running curl in the background? If not, just put the mv command on the next line, or after a ; (or, better yet, &&). Oct 2, 2017 at 4:55

2 Answers 2

5

Why would you be using a delay, and why would you need to move the file?

Just write the file in the correct place to start with:

curl -o /path/to/correct/place/filename URL

Curl exits with a zero exit status if it terminates without error. You may use this fact to move the file into the correct location only when Curl is successful:

curl -o file URL && mv file /some/place

Or, if you need to do some error reporting:

if curl -o file URL; then
    mv file /some/place
    # or, to use sftp:
    #      printf 'put file\n' | sftp -b - user@host 
else
    printf 'Curl failed with error code "%d" (check the manual)\n' "$?" >&2
    exit 1
fi
2
  • Thanks for your input. I see that using a delay is not the way to go. I need to move/copy the file to a sftp (public key authentication is in place). Any idea what approach would be best to use? Oct 2, 2017 at 9:34
  • @Borka See the comments in the last bit of code.
    – Kusalananda
    Oct 2, 2017 at 10:09
1

Use && for curl and mv command. in this case mv will execute only if previous curl command was executed successfully.

curl .... >to_file && mv to_file /to/dest

If you need to move file across sftp server, use below command.

sftp USER@HOST:/path/in/remote/dest <<< $'put /path/to/local/to_file'

Or even directly write in remote sftp path the FILE curl will output.

sftp USER@HOST:/path/in/remote/dest <<< $'put /path/to/local/"$(curl -o FILE URL)"'
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .