如何在 Bash 中为命令的输出设置变量? [英] How do I set a variable to the output of a command in Bash?

查看:36
本文介绍了如何在 Bash 中为命令的输出设置变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的脚本,如下所示:

I have a pretty simple script that is something like the following:

#!/bin/bash

VAR1="$1"
MOREF='sudo run command against $VAR1 | grep name | cut -c7-'

echo $MOREF

当我从命令行运行这个脚本并将参数传递给它时,我没有得到任何输出.但是,当我运行 $MOREF 变量中包含的命令时,我能够获得输出.

When I run this script from the command line and pass it the arguments, I am not getting any output. However, when I run the commands contained within the $MOREF variable, I am able to get output.

如何获取需要在脚本中运行的命令的结果,将其保存到变量中,然后将该变量输出到屏幕上?

How can one take the results of a command that needs to be run within a script, save it to a variable, and then output that variable on the screen?

推荐答案

除了反引号 `command`命令替换 可以使用 $(command)"$(command)",我觉得它更容易阅读,并且允许嵌套.

In addition to backticks `command`, command substitution can be done with $(command) or "$(command)", which I find easier to read, and allows for nesting.

OUTPUT=$(ls -1)
echo "${OUTPUT}"

MULTILINE=$(ls 
   -1)
echo "${MULTILINE}"

引用 (") 对保留多行变量值很重要;它在赋值的右侧是可选的,如 不进行分词,所以OUTPUT=$(ls -1) 可以正常工作.

Quoting (") does matter to preserve multi-line variable values; it is optional on the right-hand side of an assignment, as word splitting is not performed, so OUTPUT=$(ls -1) would work fine.

这篇关于如何在 Bash 中为命令的输出设置变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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