Linux paths, filenames and base directories

Sometimes – when geeking around in Linux – you need to play with things like filenames, paths and so on. Here’s a quick reference that uses readlink, basename and dirname commands.

You have a folder structure like, say:

   |_ goofy.txt
   |_ test/
       |_ mickey.txt

Now, let’s get inside:

cd /opt

and let’s start playing:

# Get absolute path of goofy.txt</span>
readlink -f goofy.txt          # Gives: /opt/goofy.txt
# ...and of mickey.txt
readlink -f test/mickey.txt    # Gives: /opt/test/mickey.txt

# Get filename for mickey.txt without extension
basename test/mickey.txt .txt    # Gives: mickey

# Get base directory relatively to the current directory
dirname goofy.txt          # Gives: .
dirname test/mickey.txt    # Gives: test
#...and then absolutely
dirname "$(readlink -f goofy.txt)"        # Gives: /opt
dirname "$(readlink -f test/mickey.txt)"  # Gives: /opt/test

As you can see, it’s just…for playing 🙂


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s