Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get path of current file being sourced

Tags:

vim

I am sourcing a local vimrc using the plugin from the first response here: Vim: apply settings on files in directory

Now what i'd like to do is to add the curren path of this local vimrc file to vims path.

I do know that %:p:h gives me the path of the current file. But it is of the file being opened not of the config file being soucred.

let s:local_path = expand('%:p:h')
exec "set path+=".s:local_path

Does anyone know how to get the path of the file being sourced?

like image 526
RedX Avatar asked Dec 20 '12 16:12

RedX


People also ask

How do you find the directory of a file in bash?

You can use $BASH_SOURCE : #!/usr/bin/env bash scriptdir="$( dirname -- "$BASH_SOURCE"; )"; Note that you need to use #!/bin/bash and not #!/bin/sh since it's a Bash extension. When I do ./foo/script , then $(dirname $BASH_SOURCE) is ./foo .

How do I print the path of a bash script?

In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.

What is $( dirname $0?

What is dirname $0 in shell? The dirname $0 command returns the directory where the Bash script file is saved. We can return a relative path or an absolute path. This all depends on how the bash script is called.

What does source () do?

source command executes the provided script (executable permission is not mandatory) in the current shell environment, while ./ executes the provided executable script in a new shell. source command do have a synonym . filename . To make it more clear, have a look at the following script, which sets the alias.


1 Answers

Instead of %, just use the special <sfile>; in a script (but not inside a function within a script!), it is expanded to the file name of the sourced script:

:let s:local_path = expand('<sfile>:p:h')
like image 189
Ingo Karkat Avatar answered Oct 26 '22 03:10

Ingo Karkat