Rakesh
Rakesh

Reputation: 77

How to create an bash alias for the command "cd ~1"

In BASH, I use "pushd . " command to save the current directory on the stack. After issuing this command in couple of different directories, I have multiple directories saved on the stack which I am able to see by issuing command "dirs". For example, the output of "dirs" command in my current bash session is given below -

0 ~/eclipse/src
1 ~/eclipse
2 ~/parboil/src

Now, to switch to 0th directory, I issue a command "cd ~0". I want to create a bash alias command or a function for this command. Something like "xya 0", which will switch to 0th directory on stack. I wrote following function to achieve this -

xya(){
cd ~$1
}

Where "$1" in above function, is the first argument passed to the function "xya".

But, I am getting the following error -

-bash: cd: ~1: No such file or directory

Can you please tell what is going wrong here ?

Upvotes: 2

Views: 565

Answers (2)

William Pursell
William Pursell

Reputation: 212208

You can let dirs print the absolute path for you:

xya(){
    cd "$(dirs -${1-0} -l)"
}

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295278

Generally, bash parsing happens in the following order:

  • brace expansion
  • tilde expansion
  • parameter, variable, arithmetic expansion; command substitution (same phase, left-to-right)
  • word splitting
  • pathname expansion

Thus, by the time your parameter is expanded, tilde expansion is already finished and will not take place again, without doing something explicit like use of eval.


If you know the risks and are willing to accept them, use eval to force parsing to restart at the beginning after the expansion of $1 is complete. The below tries to mitigate the damage should something that isn't eval-safe is passed as an argument:

xya() {
  local cmd
  printf -v cmd 'cd ~%q' "$1"
  eval "$cmd"
}

...or, less cautiously (which is to say that the below trusts your arguments to be eval-safe):

xya() {
  eval "cd ~$1"
}

Upvotes: 4

Related Questions