“找不到命令";当输出存储在变量中时,通过管道传递变量以剪切 [英] "Command not found" piping a variable to cut when output stored in a variable
问题描述
在bash脚本中,我使用一个变量来保存这样的路径:
In a bash script I am using a variable to hold a path like this:
MY_DIR=/just/a/string/to/my/path
我想删除它的最后两个部分,所以它看起来像这样:
And I want to remove the last two parts of it so it looks like this:
/just/a/string
我正在使用剪切"操作,如下所示:
I am using 'cut' to do it, like this:
echo $MY_DIR | cut -d'/' -f-4
输出是我期望的.美好的.但是我想存储在另一个变量中,像这样:
The output is what I expect. Fine. But I want to store in an other variable, like this:
MY_DIR2=$($MY_DIR | cut -d'/' -f-4)
执行脚本时出现错误:
... /just/a/string/to/my/path: No such file or directory
为什么带有回声的直接输出有效,但将输出存储在变量中却不能呢?
Why is the direct output with echo working, but storing the output in a variable is not?
推荐答案
您需要使用管道将输入字符串传递给shell命令,在这种情况下, cut
或任何标准的shell命令会读取stdin和 acts 就可以了.您可以使用管道的一些方法来实现此目的
You need to pass an input string to the shell command using a pipeline in which case cut
or any standard shell commands, reads from stdin and acts on it. Some of the ways you can do this are use a pipe-line
dir2=$(echo "$MY_DIR" | cut -d'/' -f-4)
(或)使用here-string(它是内置的shell)而不是启动外部shell进程
(or) use a here-string which is a shell built-in instead of launching a external shell process
dir2=$(cut -d'/' -f-4 <<< "$MY_DIR")
这篇关于“找不到命令";当输出存储在变量中时,通过管道传递变量以剪切的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!