I wanted to make an alias cd that will immediately list the directories.

I tried all the following options:

 alias 'cd'='cd $1; l' alias 'cd'='cd $1; l $1' alias 'cd'='cd $1 && l' alias 'cd'='cd $1 && l $1' 

Where, l (lowercase “L”) is the alias of another application ( tree ).

Always overloaded the terminal, so for sure, since . ~/.bash_aliases . ~/.bash_aliases for some reason does not work for me.

All the above aliases when entering cd / list the list of directories / files at the mount point / , however, the directory does not change.

Then I tried to prescribe a function in the same .bash_aliases (both in turn ):

 cd() { cd $1 l } function cd() { cd $1 l } 

As a result, when executing the cd / command "hangs" ...

The only way I found this is to do this:

 cdl() { cd $1 l } 

That is, to set a different name ... But at the same time, if you go back to the first variant of the alias:

 alias 'cd'='cd $1; l' 

This is where cd works when you enter cd / , since l lists the list of directories / files along the path / , so why does it return back to the home directory?

    1 answer 1

    1. A shell alias is not a function or a program. the pseudonym has no arguments, its description is only substituted into the command instead of its name. therefore, if you have defined, for example, the following alias :

       $ alias cd='cd $1; ls' 

      then when you enter the command

       $ cd /tmp 

      it is converted to

       $ cd ; ls /tmp 

      notice the empty space after cd - nothing will be inserted there (instead of $1 ), because the variable $1 does not contain any value.

      as a result, your home directory will become your current directory (this is how the internal cd works, if no parameters are passed to it), and then the ls /tmp will be executed.

    2. when you define a function:

       $ function cd() { cd $1; ls; } 

      The cd $1 inside its body is treated as a recursive call to the same function, and this is what happens. By the way, note that such a recursion does not occur in the body of the pseudonym - cd $1 is interpreted there as referring to the internal command of the cd shell .


    and finally, in the form of an optional supplement to the answer to the question “why,” I will give an example of how to make “work the way you want”:

     $ function cd() { command cd "$@"; ls; } 
    1. it is necessary to use the function (by the way, the function keyword itself is optional in this case) to get and process the list of arguments.
    2. to call an internal shell command, you must use the internal command command .
    3. It is better to transfer not only the first argument, but all the arguments ( $@ ), and for special characters (for example, spaces / quotes, etc.) to be correctly processed inside the arguments, the list should be enclosed in double quotes ( "$@" ).