Parent directory linux command

get parent directory of a file in bash

I am more interested getting the canonical location on the file system than in traversing the path stated in the filename. Note that there are similar questions to this one, but none of them focuses on correctness, relative/absolute paths and «unsafe» names: [1] bash get the parent directory of current directory [2] Retrieve parent directory of script [3] bash filepath to parent directory of file

Are you looking for the full pathname of the directory that contains a file, or the parent of the directory containing the file? Are you more interested in traversing the path stated in the filename, or getting the canonical location on your filesystem?

Suppose your current directory is /home/user/bin and the ‘file name’ is .. (the parent current directory). Presumably, the directory containing that entry is /home/user/bin so the parent directory is /home/user , or is there some other interpretation required (the directory .. is /home/user so the parent directory is /home , perhaps). I think the ‘presumed’ variant is correct, and similarly with . , but maybe it is as well to check.

What is the approved interpretation of the -rf…/test.zip name? Is that a directory name with blanks, dashes and so on in it? Also, what should be done if the file name doesn’t exist? Is that an error, or should the code make a textual analysis of the file name to try and deduce what would be the name if the file existed?

@JonathanLeffler As for «what if file does not exist» — I honestly don’t know. SO questions tend to overgrow the original author-s intent, at least for the worthwile questions. So my interpretation and yours may vary. I personally know a file exists and these cases are indistinguishable for me.

2 Answers 2

Get parent directory of your current directory:

parent_dir="$(dirname -- "$(realpath -- "$PWD")")" 

Get the directory of the script you’re running:

parent_dir="$(dirname -- "$(realpath -- "$0")")" 

Get parent directory of anything:

parent_dir="$(dirname -- "$(realpath -- "$file_or_dir_name")")" 

If your system does not have realpath but does have readlink , this should work:

parent_dir="$(dirname -- "$(readlink -f -- "$file_name")")" 

This was a bash question. I use bash on OS X, FreeBSD and other operating systems that are not Linux which do not have the realpath command you’re suggesting, which is not part of bash. Heck, even on the Linux systems I administer, realpath is available but not installed by default. If you DO feel the need to suggest things that only work on one particular platform, at least mention the platform.

@kdhp: Even though macOS Sierra (and Mac OS X before it) are derived from BSD, they do not include a realpath command by default. On my machine, I have my implementation of the command and the GNU implementation of the command. And, given that realpath is not standardized (e.g. by POSIX), it is unlikely that the FreeBSD and GNU implementations are fully compatible. With luck, they have a common subset of functionality, though. There is a readlink command on macOS, but it has far fewer options than GNU’s version does (it has the -n option, which appears to be the same on both).

Читайте также:  Welcome to My Website!

@kdhp: This is not really an argument, but an FYI … Interesting history! Also, the macOS readlink has precisely one option ( -n for no newline); GNU readlink has 8 options (each with a long name and a short single-character name) plus —help and —version . Of these, the -n ( —no-newline ) option is the same between the two. I’m not sure whether the 7 options are the ‘legacy edge cases’ you mention. I agree that the core functionality of realpath the command is based on realpath the function. Maybe I’ll delete this after the movie. it’s not dreadfully important.

Bash’s cd command has a couple of interesting but little-used options, -P and -L .

 cd [-L|[-P [-e]] [-@]] [dir] . The -P option causes cd to use the physical directory structure by resolving symbolic links while traversing dir and before processing instances of .. in dir (see also the -P option to the set builtin command); the -L option forces symbolic links to be followed by resolving the link after processing instances of .. in dir. . 

So . if you’re looking for the physical location in the filesystem of your current working directory, you could use something like this:

In your comments, you mentioned that you’re looking for the parent directory of the directory containing a file — so, if a path is /foo/bar/baz/filename , you’d be looking for /foo/bar .

To get this, I would suggest a combination of cd -P and parameter expansion. Since you know that the / character can never exist as part of a filename, the following might work for you:

This works by using cd -P to «get» the physical location of the file, then parameter expansion to strip off the last item in the path.

$ mkdir -p one/two/three $ touch one/two/three/foo $ ln -s one/two/three bar $ ls -l bar lrwxr-xr-x 1 ghoti wheel 13 Nov 19 23:05 bar -> one/two/three $ grandparent bar/foo /usr/home/ghoti/tmp6/one/two 

Источник

Linux cd command

Computer Hope

On Unix-like operating systems, the cd command («change directory») changes the shell’s current working directory.

This page covers the bash built-in version of cd.

Description

cd is among the commands you use most on the command line. It changes your working directory. Use it to move around in the hierarchy of your file system.

Syntax

cd [-L | -P [-e]] directory

Options

-L Force symbolic links to be followed. In other words, if you tell cd to move into a «directory», which is actually a symbolic link to a directory, it moves into the directory the symbolic link points to. This option is the default behavior of cd; normally, it always acts as if -L was specified.
-P Use the physical directory structure without following symbolic links. In other words, only change into the specified directory if it actually exists as named; symbolic links are not followed. This option is the opposite of the -L option, and if they are both specified, this option is ignored.
-e If the -P option is specified, and the current working directory cannot be determined, this option tells cd to exit with an error. If -P is not specified with this option, this option has no function.

Directories

To help you organize your files, your file system contains special files called directories. Think of them like folders in a file cabinet: they have names, like files, but their function is to «contain» other files, and other directories. In this way, you can keep the files on your system separate and sorted according to their function or purpose.

Читайте также:  Use expect on linux

All files and directories on your system stem from one main directory: the root directory. There are no directories «above» the root directory; all other directories are «below» the root directory.

Any directory contained inside another directory is called a subdirectory. Subdirectories «branch» off the «root» of the directory «tree.» Unlike a real tree, directory trees are upside-down: the root is at the top and the branches reach down. When you move into a subdirectory, you are moving «down» the tree; when you move into a directory’s parent directory, you are moving «up» the tree.

All directories on your file system are subdirectories of the root directory.

By default, when you open a terminal and begin using the command line, you are placed in your home directory.

How directories are represented

Directories are separated by a forward slash («/«). For instance, the directory name «documents/work/accounting» means «the directory named accounting, which is in the directory named work, which is in the directory named documents, which is in the current directory.»

To change into this directory, and make it our working directory, we would use the command:

cd documents/work/accounting

If the first character of a directory name is a slash, that denotes that the directory path begins in the root directory. So, in contrast to the example above, the directory name «/documents/work/accounting» (note the beginning slash) means «the directory named accounting, which is in the directory named work, which is in the directory named documents, which is in the root directory.»

To change into this directory, making it our working directory, we would use the command:

cd /documents/work/accounting

The root directory

The root directory is the first directory in your filesystem hierarchy. All other directories are subdirectories of the root directory.

The root directory is represented by a single slash («/«).

To change into the root directory, making it your working directory, use the command:

You cannot make any changes to the root directory on your system unless you are logged in as root, or using the sudo command. Unless you are certain of what you’re doing, don’t make any changes here. Making a mistake could destroy your system!

The working directory

The current directory, regardless of which directory it is, is represented by a single dot («).

. would change us into the current directory. In other words, it would do nothing.

What’s actually happening is the dot represents the «assumed» directory; it’s a placeholder, and you can use the dot anywhere in a directory name. So, the command:

. is the same as the command:

In all of these examples, the dot represents «the directory assumed to be there». You can use it as a placeholder anywhere you want to tell the shell that a directory goes in that place, and to assume the appropriate value.

The parent directory

The parent directory of the current directory — in other words, the directory one level up from the current directory, which contains the directory we’re in now — is represented by two dots («..«).

So, If we were in the directory /home/username/documents, and we executed the command:

Читайте также:  Information about cpu linux

. we would be placed in the directory /home/username.

The double-dot («..») directory notation can be used anywhere in a directory name to represent going up one level. For instance, if we have two directories, /home/username/documents and /home/username/downloads, and we are currently in /home/username/documents, we could type the following:

. and we would be placed in /home/username/downloads.

Another «useless» command, but one that illustrates the way you can use the double-dot notation, is this one:

. which will place us in the directory one level above the subdirectory documents — in other words, the current directory. Note that this only work if the subdirectory documents already exists.

. is functionally the same as this command:

Your home directory

Your home directory is the directory you’re placed in, by default, when you open a new terminal session. It’s the directory that holds all your settings, your mail, your default documents and downloads folder, and other personal items. It has a special representation: a tilde («~«).

So, if our username is username, and our home directory is /home/username, the command:

. is functionally the same as the command:

. and we can always access the subdirectories of our home directory by placing the tilde as the first component of the directory name. For instance, if your documents folder is named /home/username/documents, you can always move into that directory using the command:

The previous working directory

After you change directory, you can change back to the previous working directory by representing it with a dash (««). When you do this, the shell automatically tells you the new directory name.

Источник

Get the parent directory of a given file [duplicate]

Do you ever search before asking or ask basic questions just for the upvotes? It’s hard to believe you couldn’t find this doing a little searching.

5 Answers 5

(at least GNU dirname takes options, so the — is required in case the path starts with a dash.)

@gardenhead, only for demonstration. Of course really we’d just do somecommand «$» (And even for printing, printf would arguably be better.)

If you are using zsh try :h modifier

You can add n of them to go n levels up in directory structure.

Also works in csh / tcsh where it comes from though in those shells, you’ll need to add a :q to account for directory names that contain blanks or wildcards.

this is quite simple with the command dirname, just do the folowing:

now you can even go further on this

file=/home/switch87/.bashrc cd "$(dirname -- "$file")" cd "$(dirname -- "$file")"/.. 

first cd will get you to /home/switch87, the seccond to /home

get the directory of the file in a very general way (when file is known with a relative or absolute pathname, or no path at all):

the_dir="$(cd -P -- "$(dirname -- "$")" && pwd)" 

So to get the parent of that directory:

the_parent_dir="$(cd -P -- "$(dirname -- "$")/.." && pwd)" 

cd -P : print the «real» (physical) path, instead of a path using symbolic links. If you take the -P out it also works, but you may get a different result ( for exemple: cd / ; ln -s /long/path/here shortcut ; cd shortcut ; pwd will show you the path: /shortcut , whereas if you added -P to cd you would see /long/path/here instead)

Источник

Оцените статью
Adblock
detector