在 OS X 中的 bashrc 函数之后防止 'process completed'

Preventing 'process completed' after bashrc function in OS X

在我的 .bashrc 文件中,我有以下几行:

alias cd='_cd'

function cd() 
{
    cd ""
    PS1='[$USER] "$PWD" $ '
}

然而,在获取我的 .bashrc 之后,每次我尝试 运行 命令时,我都会收到一条进程已完成的消息,并且我被锁定在 shell 之外。

[prompt] $ source ~/.bashrc
[prompt] $ cd ~

[Process completed]

如何在没有收到流程完成消息的情况下轻松实现此功能?

声明 alias cd='_cd' 并不意味着您要将内置命令 cd 更改为 _cd。这意味着您正在创建 _cd 的别名,当您输入 cd 时将调用该别名。命令扩展遵循 $PATH 中的别名、函数、内置函数和可执行文件的顺序。所以如果有同名的别名、函数和内置函数,就会执行别名。

接下来您似乎正在尝试使用一个函数来设置您的 PS1,而正如 Jonathan 所解释的那样,最好在您的 .bashrc 中简单地声明它,例如

PS1='[$USER] "$PWD" $ '

但是我建议使用提示识别的特殊字符而不是系统变量。

$USER is the current user, which in PS1 can represented by \u
$PWD is the working directory, you have the option here to show the full path with \w or just the current with \W.
There are a lot of other useful options, but you should check them out by yourself.

https://www.gnu.org/software/bash/manual/bashref.html#Controlling-the-Prompt

因此您的提示可能类似于 PS1=[\u] \w $

您的 cd 函数是递归的,最终 shell 变得太深而放弃。

确保您在函数内部调用 shell 的 cd

cd() {
    builtin cd ""
    PS1='[$USER] "$PWD" $ '
}

如果您使用以下方式定义提示,则不必执行此操作:PS1='[\u] "\w" $ ' -- 请参阅 bash 手册页的提示部分。