1

I'm trying to get the string "boo" from "upper/lower/boo.txt" and assign it to a variable. I was trying

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

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

jyu429
  • 71
  • 2
  • 5

1 Answers1

7

Don't do it that way at all. Much more efficient is to use built-in shell operations rather than out-of-process tools such as cut and rev.

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

See BashFAQ #100 for a general introduction to best practices for string manipulation in bash, or the bash-hackers page on parameter expansion for a more focused reference on the techniques used here.


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

var=$(command_goes_here)

...is the correct syntax. By contrast:

var= $(command_goes_here)

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


To show yet another variant,

var = command_goes_here

...runs var as a command, with = as its first argument, and command_goes_here as a subsequent argument. Which is to say, whitespace is important. :)

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • this great answer prompts me a question: if I say `var=3 echo "$var"`, should it return `3`? It returns nothing. – fedorqui Jun 20 '15 at 12:11
  • 1
    @fedorqui, ...because variables set that way are in the environment only, and not available at expansion time. Yes, that's expected behavior. – Charles Duffy Jun 20 '15 at 14:42
  • 1
    @fedorqui, ...by contrast, compare to `var=3 sh -c 'echo "$var"'`. – Charles Duffy Jun 20 '15 at 19:15
  • Oooh that's it! I was doing many tests and couldn't find the way. So let's see if I understand your solution: by saying `var=3` we define the variable in the environment, which is "copied" or "received" by the subshell we open with `sh -c`. – fedorqui Jun 20 '15 at 19:20
  • 1
    Right. You can also see it in the output of `var=3 env`. – Charles Duffy Jun 20 '15 at 19:22
  • Many thanks. I will try to add a question about this, so that we can move this interesting comments by you into a place where they can be better found. Will try in a couple of days. – fedorqui Jun 20 '15 at 19:30
  • I posted the question! [Assign and use of a variable in the same subshell](http://stackoverflow.com/q/30982767/1983854). – fedorqui Jun 22 '15 at 15:46