Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

bash - 如何在Bash中将变量设置为命令的输出?(How do I set a variable to the output of a command in 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

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.

(但是,当我运行$MOREF变量中包含的命令时,我可以获取输出。)

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?

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

  ask by John translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In addition to backticks `command` you can use $(command) or "$(command)" which I find easier to read, and allow for nesting.

(除了反引号`command`您还可以使用$(command)"$(command)" ,我觉得它们更易于阅读,并且可以嵌套。)

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

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

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

(引号( " )对于保留多行值确实很重要。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...