tail does not provide output in bash scripts
I’ve written a bash script to filter the “tail” output, and that’s the whole command
tail -f /var/log/asterisk/messages | awk 'match($12, /[^0-9]91([0-9]{10})@default/, a) {print a[1]}'
Works fine in the CLI, but not in a bash script:
#!/bin/bash
phonenumber=$(tail -f /var/log/asterisk/messages | awk 'match($12, /[^0-9]91([0-9]{10})@default/, a) {print a[1]}')
echo "$phonenumber >> test.log"
It doesn’t output anything, (2135551234, is the expected output string) I’ve tried writing to a log file and only writing standard output but none of them work.
I’ve tried writing scripts using “cat” instead of “tail” and it works great. But I don’t want to dump the output of the entire file, so “tail” is used.
I’ve also tried using ‘tee’ but to no avail
The ultimate goal of this script is to send the phone number entering the PBX to a serial device to another system and use as a CID.
Thank you in advance for all your help
Solution
Try this :
phonenumber=$(tail -f /var/log/asterisk/messages | awk 'match($12, /[^0-9]91([0-9]{10})@default/, a) {print a[1]; exit}')
Your version doesn’t work because tail -f
and awk
are in an infinite loop. Adding exit
to the awk
script terminates the loop when the first phone number is found. awk
immediately exits and puts its output into a variable, and tail -f
gets a SIGPIPE signal when trying to write the next line to the pipe, which causes it to exit.