File Empty While Script Running

About writing shell scripts and making the most of your shell
Forum rules
Topics in this forum are automatically closed 6 months after creation.
Locked
gkelley
Level 1
Level 1
Posts: 26
Joined: Mon Aug 21, 2017 7:34 pm

File Empty While Script Running

Post by gkelley »

I have an app that is a client process that needs to run in background. It outputs a url to STDOUT when launched.

I have a short script that runs the client app and redirects output to a file then goes to background

When I display the file with 'cat' in the script it is empty but displays the url if I run cat after the script ends.

test.sh
#!/bin/bash
clientapp > url.tmp &
cat url.tmp
exit

I can cat url.tmp and see url after I run test.sh but not inside script. Normal? Any way to force file closed so I can cat in script?

Thanks, has me stumped (not a scripting whiz, know just enough to get me into trouble)
Last edited by LockBot on Sat Feb 11, 2023 11:00 pm, edited 3 times in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
User avatar
Coggy
Level 5
Level 5
Posts: 615
Joined: Thu Mar 31, 2022 10:34 am

Re: File Empty While Script Running

Post by Coggy »

The script is running testapp in the background (the & symbol says to launch testapp in the background). I think it is probably running cat against the empty file before testapp has finished loading. Welcome to the joys of concurrent processing. Unless there is a good reason for the script carrying on before testapp finishes, I suggest you don't run it as a background process. If there is good reason, perhaps "sleep 1" before cat might help, but might not. If testapp doesn't flush its output stream buffer after finishing outputting that one line, then it likely won't appear in the file until testapp terminates, whatever you do.
gkelley
Level 1
Level 1
Posts: 26
Joined: Mon Aug 21, 2017 7:34 pm

Re: File Empty While Script Running

Post by gkelley »

Thanks. Thought I had tried sleep before, but tried it just now and that solved the problem.
User avatar
it-place
Level 3
Level 3
Posts: 189
Joined: Thu Jul 05, 2018 4:42 am

Re: File Empty While Script Running

Post by it-place »

Hi gkelley,

the cat command is starting too fast so your file test.tmp exists but it is still empty. If you add the command sync between creating the file and the cat command your script will write the file down to disk and give it out to the screen:

Code: Select all

#!/bin/bash
testapp > test.tmp &
sync
cat test.tmp
exit
Regards - Olli
User avatar
it-place
Level 3
Level 3
Posts: 189
Joined: Thu Jul 05, 2018 4:42 am

Re: File Empty While Script Running

Post by it-place »

Another idea is to use the tee command so you do not need to cat the output at all:

Code: Select all

#!/bin/bash
testapp | tee test.tmp
exit
In this example the output of testapp is going to STDOUT and to your file test.tmp for later use. :)
Locked

Return to “Scripts & Bash”