Going to the parent directory of a file with cd?
18,004
Solution 1
Type cd $( dirname /path/to/file.end)
. That will take you into /path/to
.
Explanation:
-
dirname
returns the complete path for a file (without the filename, which you would get withbasename
) - i.e.dirname /etc/apt/apt.conf.d/99update-notifier
returns/etc/apt/apt.conf.d
- the expression
$(anything)
is replaced by the result of the command in the parentheses. Socd $( dirname /etc/apt/apt.conf.d/99update-notifier)
is executed ascd /etc/apt/apt.conf.d
Another (but old and discouraged) notation for the same was
cd `dirname /path/to/file.end`
Solution 2
You can not cd
into a file. Here is a (command line) function that will automatically cd
into a path for a given fully qualified file path:
function fcd () { [ -f "$1" ] && { cd "$(dirname "$1")"; } || { cd "$1"; } ; pwd; }
Solution 3
If you append "/.." to the filename that will take you to the correct directory e.g. cd /path/to/file.end/..
. It works on Cygwin anyway.
Related videos on Youtube
Author by
Azsgy
Updated on September 18, 2022Comments
-
Azsgy over 1 year
I am writing a .sh to do some work for me, but I am now at the point where I have to cd to the directory the file /path/to/file.end is in. terminal doesn't allow
cd /path/to/file.end bash: cd: /path/to/file.end: Not a directory
there is sadly no workaround I know of, so it would be nice if you could help!
-
Admin almost 11 yearsUm, do you mean
cd /path/to
? That will change the directory to the directory that the filefile.end
is in. -
Admin almost 11 yearsNo, the file is variable, and I would like to enter the path of the file (drop it into the terminal) and then go to the folder it is in
-
-
Azsgy almost 11 yearsDid I get this right?: function fcd () { [ -f $1 ] && { cd $(/file.end $1); } || { cd $1 ; } pwd } the response is: bash: syntax error near unexpected token `pwd' it gives me an error this way :(
-
fiatux almost 11 years@Atsch, need a semicolon before
pwd
, and if you're defining a function in one line, need a semicolon afterpwd
. -
Rinzwind almost 11 yearsdarn I should have not doubted myself. The alternative looked better to me when I found it _O-
-
Rinzwind almost 11 yearsDoes not work in bash ;)
touch test && cd /home/test/test/..
saysbash: cd: /home/test/test/..: No such file or directory
-
sdaau over 9 yearsThanks, was looking for something like this - I bump into
bash: cd: Not a directory
more often than I'd like to; this might help. Cheers! -
lucidbrot about 3 yearsDoes work in windows cmd
-
Dario Seidl over 2 yearsA more robust version of this function that handles multiple arguments can be found here: stackoverflow.com/a/59049206/401712 (cd is not commonly used with multiple arguments, but it's still good to support them)