Jacob
Jacob

Reputation:

Bash: Can anyone figure out the meaning of this line?

cd $(dirname $(readlink -f $0))

It is part of a larger script file, but appears at the very beginning, right after #!/bin/bash

Upvotes: 4

Views: 13767

Answers (3)

user836352
user836352

Reputation:

This appears to change your shell's working directory to the directory where the script is stored. This is probably done so that the script can refer to other things in the same directory as itself.

I've used a variant of this before, location=$(dirname $0). This does not change the directory, but rather stores the script's path for later use. dirname $0 takes a filename (in this case, $0 or the path where the shell found that file), and echoes the directory that it is stored in. Wrapping a command (or a sequence of commands) in a $() combination causes the output of the command (whatever is printed to the screen by echo, df, cat, etc) to replace that expression using $(). Example: variable=$(echo "test") becomes variable="test"

As in other programming languages, $() can be nested. An example is: variable=$(echo $(echo "test")) The inner-most expression will print 'test', which will then be substituted as the argument to the outermost echo. The output of this echo will then be substituted as the value to store in variable - the result of the first and second example will be identical. A stupid example. but it works.

The only different between $(dirname $(readlink -f $0)) and $(dirname $0) that I can see is that the former always returns the absolute path. The latter can return the relative path or the absolute path, depending on where the working directory is in relation to the script.

Upvotes: 10

A.H.
A.H.

Reputation: 66283

Adding to @user606723: $0 contains the path and/or filename of the invoked script1. The readlink -f $0 will make that path absolute and will also resolve any symlinks in this name - both intermediate directories and the final part also. From that part dirname will return only the directory part.

This is a good technique for writing "startup scripts" for applications. The script can be symlinked from some private bin directory and the script does not assume a certain install location of the application.


1The gory details about the contents of $0, when it is absolute, when not, when it contains a path or not and so on depend on the way the calling shell found the script. The comments shed some light on it.

Upvotes: 3

user606723
user606723

Reputation: 5145

  • The command does readlink -f $0, which seems to return a path
  • dirname takes that path, and gives you the dirname
  • cd changes directory to that dirname
  • $0 is a variable that holds the name of the current script as it was invoked.

See:

  • man readlink
  • man dirname
  • man cd

Upvotes: 5

Related Questions