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?

2

1 Answer 1

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.

1
  • Very userful answer. Thanks!
    – jambodev04
    Commented Jan 17, 2020 at 18:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .