问题
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