Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

scripting

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

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


2 Answers

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.

  • 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
like image 29
user606723 Avatar answered Oct 23 '25 22:10

user606723



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!