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?
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?
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. :)