bash Linux Shell 脚本:将命令输出保存在变量/文件中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20253270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Linux Shell Script: Save command outputs in variable/file?
提问by user2966991
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.
该脚本通过 telnet 连接到指定的服务器并执行不同的命令。进一步的命令需要一个命令。嗯...我必须从命令输出中保存这些信息。
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. :(
我想将命令“clientlist”的输出保存在变量或文件中。变量将是最好的解决方案。但实际上该变量只保存“clientlist”而不是命令的输出。:(
I hope somebody can help me. Thanks in advance! :)
我希望有人可以帮助我。提前致谢!:)
If you want to test it: It's made for TeamSpeak 3 server.
如果你想测试它:它是为 TeamSpeak 3 服务器制作的。
回答by Tim Pierce
To run the command 'clientlist' and save the output in a variable:
要运行命令“clientlist”并将输出保存在变量中:
output_var=$(clientlist)
In bash or sh, the $(...)
syntax means "run this command and return whatever output it produces."
在 bash 或 sh 中,$(...)
语法的意思是“运行这个命令并返回它产生的任何输出”。
回答by pobrelkey
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.)
如果这个问题的意思是“我想clientlist
在远程机器上运行命令,然后将其输出捕获到本地机器上的一个变量”,那么你不能使用类似脚本的东西来做到这一点。(请注意,您编写的脚本仅将管道输入输入到telnet
命令中;telnet
的输出不会在任何地方捕获。)
You'll need to write a script using something like expect
, or one of its work-alikes in another language like Perlor Python.