Linux 将命令输出分配给 shell 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9936598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:30:10  来源:igfitidea点击:

Assigning command output to a shell variable

linuxtcsh

提问by Richeek

I am trying to assign output of a cut command to a variable, however I am running into a strange problem. I am using tcsh shell.

我试图将 cut 命令的输出分配给一个变量,但是我遇到了一个奇怪的问题。我正在使用 tcsh 外壳。

$echo 
$set a=`cut -f2 -d' ' test.txt`
Missing }.    //This is the output I am getting
tcsh

This is the command I am running:

这是我正在运行的命令:

{ {corner

Now the file is real simple (well this is the not the file I was working on but I reduced the problem to this.)

现在文件非常简单(好吧,这不是我正在处理的文件,但我将问题简化为这个。)

Test.txt:

测试.txt:

{ {corner}

Thats it! This is the file. If I change the file to this:

就是这样!这是文件。如果我将文件更改为:

$echo $a
corner   //Please note its not {corner} but corner

Statement works but "a" gets the following value:

语句有效,但“a”获得以下值:

set a="`cut -f2 -d' ' test.txt`"

Hence I think that shell is trying to execute {corneras a command and since its missing the closing brace shell complains. Does anyone have any idea why its showing this behavior? My understanding is that it should just assign the output of cut to the variable but looks like its assigning it recursively! Newbie

因此,我认为 shell 试图{corner作为命令执行 ,并且由于缺少右括号 shell 会抱怨。有谁知道为什么它会表现出这种行为?我的理解是它应该只将 cut 的输出分配给变量,但看起来它是递归分配的!新手

采纳答案by ring bearer

You have to wrap it around double quotes

你必须把它用双引号括起来

echo "$a"

Same applies to uses such as echo

同样适用于诸如 echo

{corner

Output

输出

##代码##