“Command not found” piping a variable to cut when output stored in a variable [duplicate]

谁说我不能喝 提交于 2021-02-16 20:17:16

问题


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)

When I execute the script I get the error:

... /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?


回答1:


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)

(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")



回答2:


Use the grave accent(`) to emulate a command, and use echo too.

MY_DIR2=`echo $MY_DIR | cut -d'/' -f-4`


来源:https://stackoverflow.com/questions/47285981/command-not-found-piping-a-variable-to-cut-when-output-stored-in-a-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!