Linux Shell Script: Save command outputs in variable/file?
Solution 1
If by this question you mean "I want to run the clientlist
command on the remote machine, then capture its output to a variable on the local machine", then you can't do this using something like your script. (Note that you script only pipes input into the telnet
command; telnet
's output isn't captured anywhere.)
You'll need to write a script using something like expect
, or one of its work-alikes in another language like Perl or Python.
Solution 2
To run the command 'clientlist' and save the output in a variable:
output_var=$(clientlist)
In bash or sh, the $(...)
syntax means "run this command and return whatever output it produces."
user2966991
Updated on June 23, 2022Comments
-
user2966991 almost 2 years
I want to use some output of a command, but I don't know, how I can save the output in a variable or file.
The script is connecting to a specified server via telnet and executes different commands. One command is needed for further commands. Well... I have to save these informations from the command output.
My code:
#!/bin/bash ( echo open server portnumber sleep 2s echo "login username password" sleep 1s echo "use sid=1" CLIENT_LIST=$(echo "clientlist") sleep 1s echo "clientupdate client_nickname=Administrator" for client_id in $(echo $CLIENT_LIST | grep -Eo "clid=[0-9]+" | grep -Eo "[0-9]+"); do echo "clientpoke clid=$client_id msg=How\sare\syou!" sleep 1s done sleep 1s echo "logout" echo "quit" ) | telnet
I want to save the output of the command 'clientlist' in a variable or file. A variable would be the best solution. But actually the variable just saves 'clientlist' and not the output of the command. :(
I hope somebody can help me. Thanks in advance! :)
If you want to test it: It's made for TeamSpeak 3 server.
-
user2966991 over 10 yearsAh, okay. Thank you. I will execute this code 3-times with different commands and will save the output of telnet in files. That's working. I thought there exists a better solution. :(