Maximiliano Padulo
Maximiliano Padulo

Reputation: 1522

Insert current path in bash command line

To run a program in bash, I normally use relative paths because it's faster to type; for example, something like

me@host:~/dir/appX$  ./manage.py runserver

The command will then be stored in the history. To recall the command from history (CTRL+R normally), I need to be on the same path as when I ran it, making the recall function less useful.

One solution is to insert the full path the first time, but it takes a lot of writing.

me@host:~/dir/appX$  /home/me/dir/appX/manage.py runserver

Is there a way (preferably built in) to insert the current path in the command line? Or maybe a better solution (should work on bash)?

Upvotes: 6

Views: 1415

Answers (1)

Vivek
Vivek

Reputation: 2020

You can do this in bash using Tilde Expansion. You need two tilde expansion related features, just showing the relevant parts from man bash below:

Tilde Expansion
    If  the tilde-prefix is a `~+', the value of the shell variable PWD
    replaces the tilde-prefix.

tilde-expand (M-&)
    Perform tilde expansion on the current word.

As it says, you can type ~+ to get the current path. And then to expand it you need to type M-&. So the key sequence ~+M-& is all you need.

I found it a little difficult pressing all these keys, so I created a key binding for this. Add a line like below in your ~/.inputrc file:

"\C-a":"~+\e&"

With this I can now type ctrl+a on my keyboard to get the current path on the command line.

PS: It's possible that ctrl+a is already bound to something else (perhaps beginning of line) in which case it might be better to use another key combination. Use bind -p to check current bindings.

Upvotes: 5

Related Questions