繁体   English   中英

如何将 shell 命令结果存储在 sql 中的变量中?

[英]How do I store shell command results in a variable in sql?

我的系统是 Ubuntu 16.04 和 MariaDB 版本是 10.2.38。

我想从 shell 获取 Ubuntu 版本并将结果保存在 sql 变量中。

MariaDB [(none)]> \! lsb_release -r;
Release:        16.04

我执行了下面的句子。

MariaDB [(none)]> set @ver = '\! lsb_release -r';
Query OK, 0 rows affected (0.00 sec)

但是存储在@ver 变量中的值让我很失望。

MariaDB [(none)]> select @ver;
+------------------+
| @ver             |
+------------------+
| ! lsb_release -r |
+------------------+
1 row in set (0.00 sec)

我想知道如何将值 16.04 保存在变量中。 谢谢。

\! 是一个 mariadb(和 mysql)命令行扩展,用于执行 shell 命令进行维护。 它将在客户端执行,而不是在服务器上执行,并且不能与 SQL 命令混合使用。

SQL 不支持执行其他程序——此功能会带来巨大的安全风险。

要将 shell 命令中的 output 存储在 SQL 变量中,您可以在启动命令行客户端时使用 --init_command 选项:

$ mariadb --init-command="set @a:=right(\"`lsb_release -r`\",5)"
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 3938
Server version: 10.10.3-MariaDB-log Source distribution

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> select @a;
+-------+
| @a    |
+-------+
| 20.04 |
+-------+

如果您使用的是上游打包 MariaDB的非维护结束版本,那么在最近的 1-2 个版本中,它最后存储在@@version中:

select RIGHT(@@version,4)

RIGHT(@@version,4)
2204

在 POSIX shell 级别回答:因为lsb_release -r打印Release: 16.04 on standard output,命令

lsb_release -r | cut -d " " -f 2

应该只打印16.04

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM