bash 如何使用cut为变量赋值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26916385/
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-09-18 11:47:31  来源:igfitidea点击:

How to assign value to variable using cut?

bashshellunixterminal

提问by Eldan Shkolnikov

Below is the command I am using to assign "yellow" to the variable yellow. I can seem to echo it out using xargs but when I assign it to yellow and then try to echo it out it prints a blank line.

下面是我用来将“黄色”分配给变量黄色的命令。我似乎可以使用 xargs 将其回显,但是当我将其分配给黄色然后尝试将其回显时,它会打印一个空行。

Below is the command. Your help is highly appreciated!

下面是命令。非常感谢您的帮助!

cut -c 2- color.txt | xargs -I  {}  yellow={};

回答by Charles Duffy

No need for xargshere:

xargs这里不需要:

yellow=$(cut -c 2- color.txt)

Because xargsruns as a subprocess, you can't actually do anything that changes the state of your shell from it -- even if you start a new shell, that shell's variables and other local state disappear when it exits. Shell assignments thus don't make sense as subcommands passed to xargs.

因为xargs作为一个子进程运行,你实际上不能做任何改变你的 shell 状态的事情——即使你启动一个新的 shell,当它退出时,该 shell 的变量和其他本地状态也会消失。因此,作为传递给 xargs 的子命令,Shell 分配没有意义。



That said, you don't really need cuteither. In native bash, using no subprocesses or external tools:

也就是说,你也不需要cut。在原生 bash 中,不使用子进程或外部工具:

read color <color.txt
yellow=${color:1}

(The 1is the same column that was 2in cut, as bash PE expressionsstart with the first character as 0).

(这12在 cut 中的同一列,因为bash PE 表达式以第一个字符开头0)。

回答by Tom Fenech

Use command substitution:

使用命令替换

yellow=$(cut -c 2- color.txt)

The $()syntax expands to the output of the command, which is then assigned to the variable.

$()语法扩展到该命令,然后将其分配给变量的输出。

回答by anubhava

You need to use:

您需要使用:

yellow=$(cut -c 2- color.txt)

xargsneeds to execute an external shell binary and yellow={}is not really a binary.

xargs需要执行一个外部 shell 二进制文件,yellow={}而不是真正的二进制文件。