如何设置等于从bash中的一种命令的输出变量? [英] How to set a variable equal to the output from a command in Bash?

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

问题描述

我工作的一个简单的脚本项目的工作,涉及到使用猛砸。我有一个pretty简单的脚本,是类似如下:

I am working on a simple scripting project for work that involves the use of Bash. I have a pretty simple script that is something like the following:

#!/bin/bash

VAR1="$1"
VAR2="$2"

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. I would like to know how one can 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?

推荐答案

在除反引号,你可以使用 $(),我觉得这更容易阅读,并允许嵌套。

In addition to the backticks, you can use $(), which I find easier to read, and allows for nesting.

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

引用()做此事preserve多行的值。

Quoting (") does matter to preserve multi-line values.

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

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