Search code examples
bashwatch

Updating variables in the watch command in bash


I have a series of directories with names in a sequence (i.e. 001 002 003 ... 999). I am running a job that works on the contents in each directory, ascending the sequence from 001 to 999. The job will echo into an output.txt file in each directory. When the job has finished working on the content in a directory, it echoes "running DIRECTORY_NAME" to the job_status.txt file in the parent directory and moves on to work on the next directory.

I would like to run a simple command that looks at the output.txt of the directory that the job is currently running in.

I tried

watch "i=$(tail -n 1 job_status.txt | awk '{print $2}'); tail $i/output.txt"

This works initially; however, when the job moves on to a new directory, $i in the watch command is not updated and I'm stuck looking at the output file from the directory that the job has already completed.

How can I solve this issue?

Many thanks

Jacek


Solution

  • You're expanding the variable even before watch executes. Use a single quote instead:

    watch 'i=$(awk "END { print \$2 }" job_status.txt); tail "$i/output.txt"'
    

    Watch calls sh -c when executing the command, so define the command as if you're calling it with sh.