Alexander
Alexander

Reputation: 1

How to write info to the file from bash script and see the result immediately?

I need help. I can't understand how I can write information to the file from bash script and see the result immediately. For example:

#!/usr/bin/env bash
PID=$$
echo "PID is $PID"
echo $PID > my_script.pid
echo "Sleeping..."
sleep 5
echo "Finished"

PID number appears in console immediately, but in the file I see it after script finished. I have Mac OS X Yosemite 10.10.3. I tried a lot of stuff with flush buffering. NO result:(

Please, help!

Update. My goal is to define if another instance of that script is still running. I decided to use pid file and condition:

PID=`cat $PID_FILE`
if ps -p $PID > /dev/null; then
     echo "script already running"
     exit 1
fi

Maybe there is a more efficient way?

Upvotes: 0

Views: 136

Answers (2)

Alexander
Alexander

Reputation: 1

Sorry for misunderstanding. Actually it works fine. The problem in GUI tool (PyCharm) where I checked out file modification. It has interesting delay. So when I check out previous PID from the same script it works fine:) Thanks a lot fernan for help;)

Upvotes: 0

fernan
fernan

Reputation: 347

You must be trying to read it too soon. To confirm that it's being written right away change the script to:

#!/usr/bin/env bash
PID=$$
echo "PID is $PID"
echo "$PID written to file." >> my_script.pid
echo "Sleeping..."
sleep 5
echo "Finished"

Then run:

touch my_script.pid
tail -F my_script.pid &
./my_script.sh

The tail -F command will run on the background and will output whatever is written to my_script.pid shortly after it's written. The delay you see is on tail, once echo returns it is written.

Upvotes: 1

Related Questions