Going to the parent directory of a file with cd?
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 directorythere is sadly no workaround I know of, so it would be nice if you could help!
23 Answers
Type cd $( dirname /path/to/file.end). That will take you into /path/to.
Explanation:
dirnamereturns the complete path for a file (without the filename, which you would get withbasename) - i.e.dirname /etc/apt/apt.conf.d/99update-notifierreturns/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` 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; } 7 If you append "/.." to the filename that will take you to the correct directory e.g. cd /path/to/. It works on Cygwin anyway.