0

In my .bashrc file, I have the following lines:

alias cd='_cd'

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

However, after sourcing my .bashrc, every time I try to run the command, I get a process completed message, and I am locked out of the shell.

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

[Process completed]

How can I easily implement this function without getting the process completed message?

  • 2
    You've defined an alias `cd` to call a function `_cd`, but you defined a function `cd` instead of `_cd`? In any case, you don't need the function to set the PWD in the prompt, do you? Just set PS1 like that in single quotes outside any function and it will work OK, won't it? And for testing, maybe you shouldn't modify the real `.bashrc`; create a new file (`bash.test` perhaps) and edit that and source that — and then add the code to the real `.bashrc` when you're confident it is all OK. – Jonathan Leffler Dec 02 '15 at 00:28

2 Answers2

2

Your cd function is recursive, and eventually the shell gets too deep and gives up.

Ensure you're calling the shell's cd inside the function:

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

You don't have to do this if you define your prompt with: PS1='[\u] "\w" \$ ' -- see the PROMPTING section of your bash man page.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
0

Declaring alias cd='_cd' does not mean you are changing the builtin command cd to _cd. It means you are making an alias of _cd that is invoked when you enter cd. Command expansion follows the order of aliases, functions, builtin and then executables in $PATH. So if there is an alias, function and builtin with the same name, the alias will be executed.

Next it seems you are trying to set your PS1 with a function, while as Jonathan explained it is better to just declare it plain in your .bashrc like

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

I would recommend however to use the special characters the prompt recognizes instead of system variables.

$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

So your prompt may be something like PS1=[\u] \w $