当前位置: 首页>>技术教程>>正文


如何为cd和ls创建别名?

ubuntuer 技术教程 , , , 去评论

问题描述

我经常在运行cd命令后运行ls命令。如何为此操作创建别名(如cs)?

最佳解决方案

来自Bash Tips and Tricks: ‘cd’ with style

Finally, I want to show you how to write your own custom replacement for the ‘cd’ command.

Do you find yourself always typing the same thing upon changing into a directory? You probably at least list the files there every time, perhaps so much that your hands automatically type ‘ls’ after every ‘cd’.

Well, by trying every way I could think of, it turns out there’s only one way to properly accomplish the goal we’re seeking. We have to create a shell function.

Shell functions are part of shell programming. Like in compiled programming languages, functions provide a sort of procedural modularizability. One can create a generic function to perform an often-used bit of logic or computation with different parameters. In this case, the parameter is the current working directory.

Here’s a simple one:

function cs () {     cd $1     ls } 

正如@geirha正确指出的那样,如果您尝试切换到名称中包含空格的目录,则上述功能将失败:

$ cs A\ B/
-bash: cd: A: No such file or directory
<current directory listing>  

您应该使用以下函数:

function cs () {
    cd "$@" && ls
    }

将该代码添加到~/.bashrc后,您应该可以这样做:

hello@world:~$ cs Documents/
example.pdf tunafish.odt
hello@world:~/Documents$

次佳解决方案

您可以在bash中使用builtin命令:

function cd() {
    new_directory="$*";
    if [ $# -eq 0 ]; then 
        new_directory=${HOME};
    fi;
    builtin cd "${new_directory}" && ls
}

第三种解决方案

使用函数而不是别名:

cs() { cd "$1" && ls; }

第四种方案

感谢Florian Diesch获取使用功能的提示。我不能使用cs作为名称,因为csound包中有一个cs命令,所以我使用了lc

我把它添加到~/.bash_aliases(nano ~/.bash_aliases):

function lc () {
    cd $1;
    ls 
}

终端需要为reset才能生效。

参考资料

本文由Ubuntu问答整理, 博文地址: https://ubuntuqa.com/article/2787.html,未经允许,请勿转载。