命令提示符中的 If-else 和错误处理
If-else and error handing in command prompt
我正在尝试检测是否某些 ruby gem 没有安装,请先安装然后再继续。
例如:
gem which rails
returns gem 的驱动程序文件 (.rb
) 在 stdout
上的路径,如果 gem 存在,如果不存在则检查抛出错误stderr
.
我该如何解决?
伪代码:
if throws "gem which example1" ( gem install example1 )
if throws "gem which example2" ( gem install example2 )
if throws "gem which example3" ( gem install example3 )
:: install other stuff
cmd 或 powershell 都可以。
我需要在 AppVeyor CI yaml 配置文件中添加这些。 AppVeyor CI 具有为 DRY'ing 安装缓存目录以提高构建性能的出色功能。所以我缓存了 gems 目录,它在 运行 构建时恢复正常,但是 gem install
无论如何都会重新安装 gem!
通过使用 powershell 运行 命令,您可以使用错误重定向来检查命令是否成功:
$gemPath = gem which example3 2>$null
if ($gemPath)
{
# We got a path for the gem driver
}
else
{
# Failed, gem might not be installed
}
说明:我们告诉 powershell 将 "gem which example3" 的结果存储在变量 $gemPath
中,但是如果出现错误,我们希望将错误重定向到变量 $null
通过使用 2>$null
您还可以将 2 替换为与您要捕获的流对应的数字(成功、错误、警告等)
* All output
1 Success output
2 Errors
3 Warning messages
4 Verbose output
5 Debug messages
这里有更多关于重定向的信息About_Redirection
尝试,在 .cmd 脚本中:
gem which rails 1>nul 2>&1
IF ERRORLEVEL 1 (gem install rails)
我在这里假设您希望 stdout
和 stderr
的输出出于此批处理脚本的目的而被扼杀 - 否则,删除 1>nul 2>&1
.
我正在尝试检测是否某些 ruby gem 没有安装,请先安装然后再继续。
例如:
gem which rails
returns gem 的驱动程序文件 (.rb
) 在 stdout
上的路径,如果 gem 存在,如果不存在则检查抛出错误stderr
.
我该如何解决?
伪代码:
if throws "gem which example1" ( gem install example1 )
if throws "gem which example2" ( gem install example2 )
if throws "gem which example3" ( gem install example3 )
:: install other stuff
cmd 或 powershell 都可以。
我需要在 AppVeyor CI yaml 配置文件中添加这些。 AppVeyor CI 具有为 DRY'ing 安装缓存目录以提高构建性能的出色功能。所以我缓存了 gems 目录,它在 运行 构建时恢复正常,但是 gem install
无论如何都会重新安装 gem!
通过使用 powershell 运行 命令,您可以使用错误重定向来检查命令是否成功:
$gemPath = gem which example3 2>$null
if ($gemPath)
{
# We got a path for the gem driver
}
else
{
# Failed, gem might not be installed
}
说明:我们告诉 powershell 将 "gem which example3" 的结果存储在变量 $gemPath
中,但是如果出现错误,我们希望将错误重定向到变量 $null
通过使用 2>$null
您还可以将 2 替换为与您要捕获的流对应的数字(成功、错误、警告等)
* All output
1 Success output
2 Errors
3 Warning messages
4 Verbose output
5 Debug messages
这里有更多关于重定向的信息About_Redirection
尝试,在 .cmd 脚本中:
gem which rails 1>nul 2>&1
IF ERRORLEVEL 1 (gem install rails)
我在这里假设您希望 stdout
和 stderr
的输出出于此批处理脚本的目的而被扼杀 - 否则,删除 1>nul 2>&1
.