Get result of AT command to a variable in Bash script

I have a simple bash script which I want to capture the result of the AT command into a variable that I can do thing with. But since the command will just "hang" there after the >/dev/ttyUSB3 and that it require me to manually hit "control-x" to exist. How do you guys do this so that it will continue the code?

#!/bin/sh

# Send AT command to modem
result=$(echo "AT+QCCID" > /dev/ttyUSB3)

# Display the result
echo "Result: $result"

Thank you!

Why are you talking explicitly about "bash script" instead of "shell scripts"? Bash is just one of the shell implementations, and not installed by default into OpenWrt. Bash has some command extensions compared to other shell implementations, so "bash advice" might differ from standard shell.

Your shebang is the normal bin/sh, not bash, so there is a discrepancy, if you really want bash-specific advice.

1 Like

sorry, new to linux and openwrt. You are right I mean shell script

#!/bin/sh

so do you know how to get at command result using the method above, into a variable?

Use sms_tool or gcom with scripts (more complex).
Example:
T=$(sms_tool -d $DEVICE at "at+qtemp")

1 Like

OMG AndrewZ, you are live saver, I've been at this for 2 days... but your method ALMOST worked!

But it seems it only capture the "last line" of the output? Do you know why?

Here is my shell script (iccid.sh)

#!/bin/sh

T=$(sms_tool -d /dev/ttyUSB3 at "at+cgdcont?")

echo $T

But if you look at the picture below. When I execute your sms-tool, it showed everything in the command prompt, but if I run the shell script, it only show last line....

nevermind, thank you all for the help, I figured out, just use

output=$(sms_tool -d /dev/ttyUSB3 at "at+cgdcont?" 2>&1) and I was able to get it all..

2 Likes

You simply need to use echo "$var" and then grep, there is no need in 2>&1 in this case.