Ala*_*ith 25 command-line bashrc bash-alias .bash-profile
几乎每次我通过命令行(即 bash)“cd”到我机器上的不同目录(在这种情况下,运行 Mac OS X 10.6.7)时,我都会立即输入“ls”以获取内容列表在那个目录中。我试图找出一种覆盖“cd”的方法,以便它更改为请求的目录,然后一次性给我列表。
我已经能够获得我正在寻找的基本功能,并将以下行添加到我的 ~/.bash_profile
function cl() { cd "$@"; ls -l; }
Run Code Online (Sandbox Code Playgroud)
这按预期工作。更改到请求的目录,然后向我显示内容。我遇到问题的地方是试图覆盖“cd”本身而不是创建新的“cl”命令。
下面的事情不工作
##### Attempt 1 #####
# Hangs the command line
function cd() { cd "$@"; ls -l; }
##### Attempt 2 #####
# Hangs the command line
function cd() { 'cd' "$@"; ls -l; }
##### Attempt 3 #####
# Does not change directory.
# Does list contents, but of the directory where you started.
function cd() { /usr/bin/cd "$@"; ls -l; }
#### Other attempts that fail in various ways #####
alias cd=cd "$@"; ls -la;
alias cd="cd '$@'; ls -la;"
alias cd='cd "$@"'; ls -la;
alias cd=/usr/bin/cd "$@"; ls -la;
Run Code Online (Sandbox Code Playgroud)
我还尝试了其他几个未列出的迭代,并创建了一个指向工作 'cl' 函数的别名。没有一个工作。
我在文档中读到的内容谈到了“cd”不能作为外部命令运行的事实(这是我理解的函数需要使用它的方式)。
所以,我目前可以使用我的“cl”命令并得到我想要的,但问题是/仍然是:
有没有办法覆盖“cd”的行为以将其更改为请求的目录,然后再做其他事情?
Gaf*_*aff 32
以下应该工作:
function cd() { builtin cd "$@" && ls -l; }
Run Code Online (Sandbox Code Playgroud)
由于该函数在一行上,请确保它;以上述方式终止,以便正常工作。
Ric*_*lka 12
我认为你陷入了一个循环。您的cd函数正在调用cd,也就是……函数。
您需要知道builtin哪个是使命令查找使用 Bash 内置函数(如 cd 而不是您的函数)的关键字
function cd
{
builtin cd "$1"
: do something else
}
Run Code Online (Sandbox Code Playgroud)
此外,/usr/bin/cd即使存在这样的命令,调用也永远不会起作用。
会发生什么:
/bash/dir。/usr/bin/cd /dir/for/cd。/usr/bin/cd去 dir /dir/for/cd。/usr/bin/cd 退出。/bash/dir,因为子进程/usr/bin/cd不能影响父进程。别名也是简单的文本替换。他们永远不能有参数。
我建议不要覆盖 cd,因为还有一些其他脚本劫持了 'cd' 功能,例如 rvm。最好选择另一个名称,例如“d”,而不是在函数中指定“builtin”类型;否则,劫机者将无法运行。我正在使用下面的代码:
function d() { cd "$@" && ls;}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15820 次 |
| 最近记录: |