将echo和cut命令分配给变量 [英] Assigning echo and cut command to a variable
问题描述
我正在尝试从 upper / lower / boo.txt中获取字符串 boo,并将其分配给变量。我正在尝试
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?
推荐答案
不要那样做。使用内置的shell操作比使用诸如$codeut 和 rev
之类的进程外工具要有效得多。 。
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%%.*}
请参见 BashFAQ#100 获得有关bash中字符串操作的最佳做法的一般介绍,或有关参数扩展的bash黑客页面,以获取有关此处使用的技术的更集中参考。
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)
...在运行 command_goes_here
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.
要显示另一个变体,
var = command_goes_here
...作为命令运行 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. :)
这篇关于将echo和cut命令分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!