I want to be able to send the command "AT+CSQ" to /dev/ttyUSB1 every 5 seconds, and log out response to a text file. I can do it manually via screen (screen /dev/ttyUSB1 and type in AT+CSQ and see the response), but how do I do this as a bash script?

Below is an example script with some logic for logging and cleanup when the script terminates (the trap command). Important trick is to keep the input from the serial port open otherwise the input from the time the port was closed could get lost.



LOGDATE="date +%Y%m%dT%H%M%S"

# write command to modem
wrmodem () {
    echo -ne "$*"'\r\n' >"$MODEM"
    log "--- sent: $*"

# log message to a logfile
log () {
    echo "$($LOGDATE) $@" >>"$LOGFILE"

# logger
    trap 'log "=== logger stopped $BASHPID"' EXIT
    log "=== logger started: $BASHPID"
    while true ; do
        if read ; then
            log "$(tr -d \\r <<<"$REPLY")"
} <"$MODEM" &

trap 'kill $LOGGERPID' EXIT

# requester
while true ; do
    wrmodem "$MODEMCMD"
    sleep $INTERVAL

The expect tool is designed for just this sort of task. man expect will get you started.

Your Answer


By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.