0

As per Change gnome-terminal title to reflect the current directory? I have tried to use:

PROMPT_COMMAND='echo -ne "\033]0;$(basename ${PWD})\007"'

... in my ~/.bashrc to indicate the name of the current directory in the gnome-terminal title bar.

For the most part it works fine; but if I try to open gnome-terminal from a directory like:

/run/user/1000/gvfs/mtp:host=%5Busb%3A001%2C008%5D/Internal shared storage/DCIM/Camera

... then it fails with:

basename: extra operand ‘storage/DCIM/Camera’
Try 'basename --help' for more information.

... every time the prompt is about to be shown in terminal.

Apparently the problem are the spaces in the directory name (even if the curly braces in ${PWD} should in principle obviate the need for quotes). So, I tried escaping with quotes, and it turns out it is not trivial (apparently just a single quote escape \"${PWD}\" does not work) - best I could get to is:

PROMPT_COMMAND='echo -ne "\033]0;$(basename \\\\"${PWD}\\\\")\007"'

... which works without an error - but it prints an extra backslash in the gnome-terminal title; for instance, in this case, the title is: Camera\.

What would be the correct construction of PROMPT_COMMAND, so it handles directories with spaces correctly, and it prints only the directory (e.g. Camera) without an appended backslash?

jeremysprofile
  • 10,028
  • 4
  • 33
  • 53
sdaau
  • 36,975
  • 46
  • 198
  • 278

1 Answers1

2

Why are you trying to escape your double quotes?

PROMPT_COMMAND='echo -ne "\033]0;$(basename "${PWD}")\007"'

would be correct. We can go through the levels of nesting:

  • top-layer single quotes. Inside single quotes, you do not need to escape double quotes. You would need to "escape" single quotes via '\'' (actually, this is string concatenation, but that's not relevant here).

  • second-layer double quotes. Inside double quotes, if you were trying to write literal ", you would need \". However, you have a third layer:

  • $() / command substitution. This layer, when executed, won't see the double quotes around it (single quotes would be a different story - you'd need '\''). Bash will correctly parse something like echo "$(echo "my variable is $foo")".


Also, the curly braces in ${PWD} have nothing to do with quotes. There is no difference between ${PWD} and $PWD from any point of view. Curly braces only come into play if your variable butts up against other "word" characters:

echo PWD_$PWD_USER_$USER // expands variables "USER" and "PWD_USER_"
echo PWD_${PWD}_USER_$USER // expands variables "USER" and "PWD"
jeremysprofile
  • 10,028
  • 4
  • 33
  • 53
  • Thanks, @jeremysprofile - I was trying to escape those `PWD` quotes, because I thought they would interfere with the double quotes right after the `-ne`; thanks to this answer, now I know better! (also I apparently mixed up what I thought I knew about curly braces) – sdaau Jul 26 '20 at 12:33