我真的很惭愧地问这个问题,但是有没有办法将MySQL输出(例如ls -l)重定向到STDOUT并同时分配给变量?我试过这个:
san@pcjq:~$ exec 5>&1
san@pcjq:~$ SQL=$(mysql -uroot -p mysql -e "SELECT Host,User,Password FROM user;" | tee >(cat - >&5))
Enter password:
Host User Password
127.0.0.1 root *CD0B39440D9701958FDA10ED6B02E3507DC28EB
% slvUser *8E6F445A9F0E7AA18DA1D830CC61B5AAC9C606
localhost root *CD0B39440D9701958FDA10ED6B02E3507DC28EB
localhost san *8E6F4A10ED6B00E7AA18DA10EDD830CC61B5AAC9C606
localhost debian-sys-maint *1BF46B679FC8911CD06712EC782E446F01201CB7
这实际上并不是我们通常在屏幕上看到的输出的确切表示。另一方面:
SQL=$(mysql -uroot -p mysql -e "SELECT Host,User FROM user;" >&2)
会在屏幕上打印正确的输出但注意到变量(显而易见的原因)。有谁知道任何解决方法?干杯!!
答案 0 :(得分:2)
回答我自己的问题:
san@pcjq:~$ SQL=$(mysql -uroot -p mysql -t -e "SELECT Host,User FROM user;" \
| tee /dev/tty) && { echo "This is the ECHO:"; echo "$SQL"; }
Enter password:
+-----------+------------------+
| Host | User |
+-----------+------------------+
| % | slvUser |
| 127.0.0.1 | root |
| localhost | debian-sys-maint |
| localhost | root |
| localhost | santanu |
+-----------+------------------+
This is the ECHO:
+-----------+------------------+
| Host | User |
+-----------+------------------+
| % | slvUser |
| 127.0.0.1 | root |
| localhost | debian-sys-maint |
| localhost | root |
| localhost | santanu |
+-----------+------------------+
-t
是神奇的选择。来自MySQL手册页:
- 表,-t
Display output in table format. This is the default for interactive use, but can be used to produce table output in batch mode.
干杯!!
答案 1 :(得分:0)
您可以执行类似
的操作# mysql -u [user] -p[password] mydb -e "select * from [table]" > out.txt
# cat out.txt
或
# echo $(mysql -u [user] -p[password] mydb -e "select * from [table]")
也许密码提示让你搞砸了。
*请记住,如果“密码”是您的密码,则必须执行此操作:
# mysql -u [user] -psecret ....
希望这有帮助, 哈林