0

If I define an alias like this in .bashrc:

alias cd="cd $1 && ls"

If I call:

cd test

It correctly shows file in test directory but no changes the current directory.

If I define a function in .bashrc:

function cd {
 cd "$1" && ls
}

Now if i call

cd test

It correctly shows file in test directory and changes the current directory to "test".

Anyone knows what is the difference?

  • This is https://unix.stackexchange.com/q/3773/5132 and https://unix.stackexchange.com/q/29060/5132 and https://unix.stackexchange.com/q/453827/5132 and https://unix.stackexchange.com/q/29060/5132 and https://unix.stackexchange.com/q/50006/5132 and https://unix.stackexchange.com/q/27559/5132 and https://unix.stackexchange.com/q/366009/5132 and … – JdeBP Jan 17 '20 at 12:29
  • Most important: alias works by replacing one string with another string. There is no logic, only string replacement. – Kamil Maciorowski Jan 17 '20 at 12:49

1 Answers1

1

In fact in your first example of alias call you made after expansion:

cd test ---> cd $1 && ls test

It is the basic difference between the bash script call and the expansion of an alias! By use of an alias your parameter is written after all the characters of the alias definition. The $1 is used literally and it is not substituted with the word test from the end. You can simply verify this by changing the order of commands in the alias definition

alias cd="ls $1 && cd"

gives you the correct change of the directory, but no directory list.

schweik
  • 1,250