Eldan Shkolnikov
Eldan Shkolnikov

Reputation: 453

How to assign value to variable using cut?

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.

Below is the command. Your help is highly appreciated!

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

Upvotes: 3

Views: 6670

Answers (3)

Charles Duffy
Charles Duffy

Reputation: 295353

No need for xargs here:

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

Because xargs runs 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.


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

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

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

Upvotes: 4

Tom Fenech
Tom Fenech

Reputation: 74595

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.

Upvotes: 4

anubhava
anubhava

Reputation: 785058

You need to use:

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

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

Upvotes: 3

Related Questions