命令的输出分配给一个变​​量,如果做的返回值分支 [英] Assign command output to a variable and do if branch on the return value

查看:74
本文介绍了命令的输出分配给一个变​​量,如果做的返回值分支的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做到以下几点事情

  X = $(some_command)
如果[$? == 0];然后
  做一点事
  回声$ X
其他
  do_something_else的
科幻

基本上,我想执行一些命令,存储输出一些变量。同时,我想基于命令成功与否分支。以上的方式工作,但看起来丑陋。它是一个更聪明的方式?

感谢。


解决方案

 如果x = $(一些命令);然后
  做一点事
  回声$ X
其他
  do_something_else的
科幻

如果命令是通过运行该命令,并测试它是否成功,并执行然后取决于它在其他分支。

I want to do the following thing

X=$(some_command)
if [ $? == 0 ]; then
  do_something
  echo $x
else
  do_something_else
fi

Basically, I want to execute some command, store the output to some variable. Meanwhile, I want to branch based on whether the command succeeded or not. The above way works, but looks ugly. Is it a smarter way?

Thanks.

解决方案

if x=$(some command); then
  do_something
  echo $x
else
  do_something_else
fi

The if command works by running the command and testing whether it was successful, and executing the then or else branch depending on it.

这篇关于命令的输出分配给一个变​​量,如果做的返回值分支的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆