批处理脚本将数据库名称变为变量

时间:2021-02-01 23:21:59

I had ran my script to get the databases name into variable to check some conditions. but when I ran the script and test echo out of the variable it doesn't work. Please look at my coding:

我运行了我的脚本以将数据库名称变为变量以检查某些条件。但是当我运行脚本并测试回显变量时,它不起作用。请看我的编码:

%mysql% -u%dbuser% -p%dbpass% -s -N -e "SHOW DATABASES" | FOR /F "usebackq" %%D IN (`findstr /V "information_schema performance_schema mysql test"`) DO SET dbname=%%D echo %dbname%

The result is:

结果是:

SET dbname=mydatabasename echo

I had put a command SETLOCAL on the header of script but no luck.

我在脚本的标题上放了一个命令SETLOCAL,但没有运气。

@echo off

SETLOCAL ENABLEDELAYEDEXPANSION

Can anyone help me to get the correct command?

任何人都可以帮助我获得正确的命令吗?

1 个解决方案

#1


You can't have two separate commands on the same line the way that you've written them. You have two options:

您不能像编写它们那样在同一行上有两个单独的命令。您有两种选择:

Option 1: Use parentheses to create a code block

选项1:使用括号创建代码块

setlocal enabledelayedexpansion
for /f "usebackq" %%d in (`findstr /V "information_schema performance_schema mysql test"`) do (
    set dbname=%%d
    echo !dbname!
)

Note that you need to enable delayed expansion and use ! instead of % to call variables that get set inside of code blocks.

请注意,您需要启用延迟扩展并使用!而不是%来调用在代码块中设置的变量。

Option 2: Use a & to join the two commands.

选项2:使用&来连接这两个命令。

for /f "usebackq" %%d in (`findstr /V "information_schema performance_schema mysql test"`) do set dbname=%%d&echo %dbname%

#1


You can't have two separate commands on the same line the way that you've written them. You have two options:

您不能像编写它们那样在同一行上有两个单独的命令。您有两种选择:

Option 1: Use parentheses to create a code block

选项1:使用括号创建代码块

setlocal enabledelayedexpansion
for /f "usebackq" %%d in (`findstr /V "information_schema performance_schema mysql test"`) do (
    set dbname=%%d
    echo !dbname!
)

Note that you need to enable delayed expansion and use ! instead of % to call variables that get set inside of code blocks.

请注意,您需要启用延迟扩展并使用!而不是%来调用在代码块中设置的变量。

Option 2: Use a & to join the two commands.

选项2:使用&来连接这两个命令。

for /f "usebackq" %%d in (`findstr /V "information_schema performance_schema mysql test"`) do set dbname=%%d&echo %dbname%