Assigning echo and cut to a variable

I am trying to get the string "boo" with "upper / lower / boo.txt" and assign it to a variable. I've tried

NAME= $(echo $WHOLE_THING | rev | cut -d "/" -f 1 | rev | cut -d "." -f 1) 

but it comes out empty. What am I doing wrong?

0
bash cut
source share
1 answer

Do not do that. It is much more efficient to use the built-in shell operations, rather than tools outside the process, such as cut and rev .

 whole_thing=upper/lower/boo.txt name=${whole_thing##*/} name=${name%%.*} 

See BashFAQ # 100 for a general overview of bash string best practices, or the bash -hackers parameter extension page for a more focused reference to the methods used here.


Now, in terms of why your source code didn't work:

 var=$(command_goes_here) 

... is the correct syntax. On the contrary:

 var= $(command_goes_here) 

... exports an empty environment variable named var while command_goes_here running, and then when running the output of command_goes_here as its own command.


To show another option,

 var = command_goes_here 

... runs var as a command with = as its first argument and command_goes_here as its next argument. That is, spaces are important. :)

+7
source share

All Articles