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?

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.

| improve this answer | |
  • Very userful answer. Thanks! – jambodev04 Jan 17 at 18:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.