如何缩短命令行提示符的当前目录?

发布于 2024-11-01 18:33:47 字数 750 浏览 3 评论 0原文

我正在使用 Ubuntu,当我处理一些深层目录层次结构时,我厌倦了 bash 中的长提示。因此,我想调整我的 PS1 以按以下方式缩短工作目录部分:

目前我有:

pajton@dragon:~/workspace/projects/project1/folder1/test$

并且想要:

pajton@dragon:~/workspace/.../folder1/test$

如果 len($PWD) 通过给定阈值,则会发生截断。我想始终保留第一个路径组件和至少一个最后一个路径组件。然后,在空间允许的情况下,从右侧添加更多组件。

这就是我目前所拥有的。它有效,但是:1)不保留第一个路径组件,2)不尊重边界处的切割路径:

pwd_length=14
pwd_symbol="..."
newPWD="${PWD/#$HOME/~}"

if [ $(echo -n $newPWD | wc -c | tr -d " ") -gt $pwd_length ]
then
   newPWD="...$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
else
   newPWD="$(echo -n $PWD)"
fi

结果:

pajton@dragon:...sth/folder1/sample$ 

提前致谢!

I am using Ubuntu and I am tired of this long prompts in bash when I am working with some deep directory hierarchy. So, I would like to tweak my PS1 to shorten the working directory part the following way:

Currently I have:

pajton@dragon:~/workspace/projects/project1/folder1/test$

and would like to have:

pajton@dragon:~/workspace/.../folder1/test$

The truncating would occur if len($PWD) passes given threshold. I want to always keep the first path component and at least one last path component. Then as space permits, add more components taking from the right.

This is what I have currently. It works, but: 1) doesn't keep first path component, 2) doesn't respect cutting path at boundaries:

pwd_length=14
pwd_symbol="..."
newPWD="${PWD/#$HOME/~}"

if [ $(echo -n $newPWD | wc -c | tr -d " ") -gt $pwd_length ]
then
   newPWD="...$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
else
   newPWD="$(echo -n $PWD)"
fi

And the result:

pajton@dragon:...sth/folder1/sample$ 

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

娇女薄笑 2024-11-08 18:33:47

对于寻找更简单的解决方案并且不需要路径中第一个目录的名称的人来说,Bash 使用 PROMPT_DIRTRIM 变量对此提供了内置支持。 来自文档

PROMPT_DIRTRIM

如果设置为大于零的数字,则该值将用作展开 \w 和 \W 提示字符串转义时要保留的尾随目录组件的数量(请参阅打印提示)。删除的字符将替换为省略号。

例如:

~$ mkdir -p a/b/c/d/e/f
~$ cd a/b/c/d/e/f
~/a/b/c/d/e/f$ export PROMPT_DIRTRIM=2
~/.../e/f$ PROMPT_DIRTRIM=3
~/.../d/e/f$ 

缺点:这取决于目录级别,而不是路径的长度,这可能是您不想要的。

优点:非常简单。只需将 export PROMPT_DIRTRIM=2 添加到您的 .bashrc 中即可。

For people looking for a much simpler solution and don't need the name of the first directory in the path, Bash has built-in support for this using the PROMPT_DIRTRIM variable. From the documentation:

PROMPT_DIRTRIM

If set to a number greater than zero, the value is used as the number of trailing directory components to retain when expanding the \w and \W prompt string escapes (see Printing a Prompt). Characters removed are replaced with an ellipsis.

For example:

~$ mkdir -p a/b/c/d/e/f
~$ cd a/b/c/d/e/f
~/a/b/c/d/e/f$ export PROMPT_DIRTRIM=2
~/.../e/f$ PROMPT_DIRTRIM=3
~/.../d/e/f$ 

Downside: It depends on the directory level, not the length of the path, which you might not want.

Upside: It's very simple. Just add export PROMPT_DIRTRIM=2 to your .bashrc.

行雁书 2024-11-08 18:33:47

对于您的情况,考虑使用 awk 而不是 sed 的脚本:

pwd_length=14
pwd_symbol="..."
newPWD="${PWD/#$HOME/~}"
if [ $(echo -n $newPWD | wc -c | tr -d " ") -gt $pwd_length ]
then
   newPWD=$(echo -n $newPWD | awk -F '/' '{
   print $1 "/" $2 "/.../" $(NF-1) "/" $(NF)}')
fi
PS1='${newPWD}$ '

对于目录 ~/workspace/projects/project1/folder1/test 的示例,它使 PS1 为: ~/workspace/... /folder1/test

UPDATE

上面的解决方案将设置您的提示,但正如您在评论中指出的那样,当您更改目录时,它不会动态更改 PS1。因此,这是当您更改目录时动态设置 PS1 的解决方案。

将这两行放入您的 .bashrc 文件中:

export MYPS='$(echo -n "${PWD/#$HOME/~}" | awk -F "/" '"'"'{
if (length($0) > 14) { if (NF>4) print $1 "/" $2 "/.../" $(NF-1) "/" $NF;
else if (NF>3) print $1 "/" $2 "/.../" $NF;
else print $1 "/.../" $NF; }
else print $0;}'"'"')'
PS1='$(eval "echo ${MYPS}")$ '

if (NF > 4 && length($0) > 14) awk 中的条件仅在当前目录大于时应用特殊处理3 个目录深,并且如果 $PWD 的长度超过 14 个字符,否则会将 PS1 保留为 $PWD

例如:如果当前目录是 ~/workspace/projects/project1$ 那么 PS1 将是 ~/workspace/projects/project1$

上述在 .bashrc 中的效果将如下在您的 PS1 上:

~$ cd ~/workspace/projects/project1/folder1/test
~/workspace/.../folder1/test$ cd ..
~/workspace/.../project1/folder1$ cd ..
~/workspace/.../project1$ cd ..
~/.../projects$ cd ..
~/workspace$ cd ..
~$

请注意当我更改目录时提示符如何变化。如果这不是您想要的,请告诉我。

Consider this script using awk instead of sed for your case:

pwd_length=14
pwd_symbol="..."
newPWD="${PWD/#$HOME/~}"
if [ $(echo -n $newPWD | wc -c | tr -d " ") -gt $pwd_length ]
then
   newPWD=$(echo -n $newPWD | awk -F '/' '{
   print $1 "/" $2 "/.../" $(NF-1) "/" $(NF)}')
fi
PS1='${newPWD}$ '

For your example of directory ~/workspace/projects/project1/folder1/test it makes PS1 as: ~/workspace/.../folder1/test

UPDATE

Above solution will set your prompt but as you noted in your comment that it will NOT change PS1 dynamically when you change directory. So here is the solution that will dynamically set PS1 when you change directories around.

Put these 2 lines in your .bashrc file:

export MYPS='$(echo -n "${PWD/#$HOME/~}" | awk -F "/" '"'"'{
if (length($0) > 14) { if (NF>4) print $1 "/" $2 "/.../" $(NF-1) "/" $NF;
else if (NF>3) print $1 "/" $2 "/.../" $NF;
else print $1 "/.../" $NF; }
else print $0;}'"'"')'
PS1='$(eval "echo ${MYPS}")$ '

if (NF > 4 && length($0) > 14) condition in awk will only apply special handling when your current directory is more than 3 directories deep AND if length of $PWD is more than 14 characters otherwise and it will keep PS1 as $PWD.

eg: if current directory is ~/workspace/projects/project1$ then PS1 will be ~/workspace/projects/project1$

Effect of above in .bashrc will be as follows on your PS1:

~$ cd ~/workspace/projects/project1/folder1/test
~/workspace/.../folder1/test$ cd ..
~/workspace/.../project1/folder1$ cd ..
~/workspace/.../project1$ cd ..
~/.../projects$ cd ..
~/workspace$ cd ..
~$

Notice how prompt is changing when I change directories. Let me know if this is not what you wanted.

执笔绘流年 2024-11-08 18:33:47

这是我根据 anubhava 的解决方案使用的。它设置提示和窗口标题。 awk 脚本更具可读性,因此可以轻松调整/自定义。

如果路径超过 16 个字符和 4 层深度,它将折叠路径。此外,它还会在...中指示折叠了多少个目录,以便您了解路径的深度,即:~/usr/..4../path2/path1 表示折叠了 4 层。

# define the awk script using heredoc notation for easy modification
MYPSDIR_AWK=$(cat << 'EOF'
BEGIN { FS = OFS = "/" }
{ 
   sub(ENVIRON["HOME"], "~");
   if (length($0) > 16 && NF > 4)
      print $1,$2,".." NF-4 "..",$(NF-1),$NF
   else
      print $0
}
EOF
)

# my replacement for \w prompt expansion
export MYPSDIR='$(echo -n "$PWD" | awk "$MYPSDIR_AWK")'

# the fancy colorized prompt: [0 user@host ~]$
# return code is in green, user@host is in bold/white
export PS1='[\[\033[1;32m\]$?\[\033[0;0m\] \[\033[0;1m\]\u@\h\[\033[0;0m\] $(eval "echo ${MYPSDIR}")]$ '

# set x/ssh window title as well
export PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME%%.*} $(eval "echo ${MYPSDIR}")\007"'

这是它实际的样子。绿色 0 是最后一个命令的返回码:

在此处输入图像描述

This is what I use based on the solutions from anubhava. It sets both the prompt and the windows title. The awk script is more readable so it can be tweaked/customized easily.

It will fold the path if it's more than 16 chars and 4 levels deep. Furthermore, it will also indicate in the ... how many directories were folded, so you get a sense of how deep the path is, ie: ~/usr/..4../path2/path1 indicates 4 levels were folded.

# define the awk script using heredoc notation for easy modification
MYPSDIR_AWK=$(cat << 'EOF'
BEGIN { FS = OFS = "/" }
{ 
   sub(ENVIRON["HOME"], "~");
   if (length($0) > 16 && NF > 4)
      print $1,$2,".." NF-4 "..",$(NF-1),$NF
   else
      print $0
}
EOF
)

# my replacement for \w prompt expansion
export MYPSDIR='$(echo -n "$PWD" | awk "$MYPSDIR_AWK")'

# the fancy colorized prompt: [0 user@host ~]$
# return code is in green, user@host is in bold/white
export PS1='[\[\033[1;32m\]$?\[\033[0;0m\] \[\033[0;1m\]\u@\h\[\033[0;0m\] $(eval "echo ${MYPSDIR}")]$ '

# set x/ssh window title as well
export PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME%%.*} $(eval "echo ${MYPSDIR}")\007"'

Here's what it looks like in action. The green 0 is the return code of last command:

enter image description here

清风疏影 2024-11-08 18:33:47
echo -n $PWD | sed -re "s|(~?/[^/]*/).*(.{$pwd_length})|\1...\2|"

sed 与 -r 只是为了方便起见,允许省略括号前的反斜杠和“|”作为分隔符也只是为了方便 - 因为我们想在命令中使用斜杠。我猜你的 home get 也显示为 ~,所以 ~/foo/bar/baz/ 应该以 ~/foo/.../baz 结尾,而 /foo/bar/baz/ 应该以 /foo/.../baz 结尾/。

所以我们采用一个可选的~,后面是斜杠,名称,斜杠作为\1,然后是一些东西,然后其余的作为\2。

echo -n $PWD | sed -re "s|(~?/[^/]*/).*(.{$pwd_length})|\1...\2|"

sed with -r only for convenience, allows to omit backslash before parentheses, and "|" as delimiter only for convenience too - because we want to use the slash inside the command. I guess your home get's displayed as ~ as well, so ~/foo/bar/baz/ should end in ~/foo/.../baz, and /foo/bar/baz/ as /foo/.../baz/.

So we take an optional ~, followed by slash, name, slash as \1, then something, then the rest as \2.

彻夜缠绵 2024-11-08 18:33:47

另一种方法,仍然使用 sed 和 awk 来生成提示符。这会将您的 $HOME 目录转换为 ~,显示您的根目录、最低级别(当前目录)及其父目录,其中每个目录用 .. 分隔之间。

.bashrc 内部(或 OS X 上的 .bash_profile):

function generate_pwd {
  pwd | sed s.$HOME.~.g | awk -F"/" '
  BEGIN { ORS="/" }
  END {
  for (i=1; i<= NF; i++) {
      if ((i == 1 && $1 != "") || i == NF-1 || i == NF) {
        print $i
      }
      else if (i == 1 && $1 == "") {
        print "/"$2
        i++
      }
      else {
        print ".."
      }
    }
  }'
}
export PS1="\$(generate_pwd) -> "

该脚本使用 awk 内置的 NF 变量(字段数)和位置变量 ($1, $2 ...) 打印由 ORS 变量(输出记录分隔符)分隔的每个字段(目录名称)。它将内部目录折叠到提示符中的 .. 中。

使用中的示例:

~/ -> cd Documents/
~/Documents/ -> cd scripts/
~/Documents/scripts/ -> cd test1/
~/../scripts/test1/ -> cd test2
~/../../test1/test2/ -> pwd
/Users/Brandon/Documents/scripts/test1/test2
~/../../test1/test2/ -> cd test3/
~/../../../test2/test3/ -> cd test4/
~/../../../../test3/test4/ -> pwd
/Users/Brandon/Documents/scripts/test1/test2/test3/test4
~/../../../../test3/test4/ -> cd /usr/
/usr/ -> cd local/
/usr/local/ -> cd etc/
/usr/local/etc/ -> cd openssl/
/usr/../etc/openssl/ -> cd private/
/usr/../../openssl/private/ ->

Another approach, still using sed and awk to generate the prompt. This will convert your $HOME directory into ~, show you your root directory, your lowest level (current directory), and its parent, separated by .. for each directory in between.

Inside of your .bashrc (or .bash_profile on OS X):

function generate_pwd {
  pwd | sed s.$HOME.~.g | awk -F"/" '
  BEGIN { ORS="/" }
  END {
  for (i=1; i<= NF; i++) {
      if ((i == 1 && $1 != "") || i == NF-1 || i == NF) {
        print $i
      }
      else if (i == 1 && $1 == "") {
        print "/"$2
        i++
      }
      else {
        print ".."
      }
    }
  }'
}
export PS1="\$(generate_pwd) -> "

The script uses awk's built in NF variable (number of fields) and positional variables ($1, $2 ...) to print each field (directory name) separated by the ORS variable (output record separator). It collapses the inner directories into .. in your prompt.

Example of it in use:

~/ -> cd Documents/
~/Documents/ -> cd scripts/
~/Documents/scripts/ -> cd test1/
~/../scripts/test1/ -> cd test2
~/../../test1/test2/ -> pwd
/Users/Brandon/Documents/scripts/test1/test2
~/../../test1/test2/ -> cd test3/
~/../../../test2/test3/ -> cd test4/
~/../../../../test3/test4/ -> pwd
/Users/Brandon/Documents/scripts/test1/test2/test3/test4
~/../../../../test3/test4/ -> cd /usr/
/usr/ -> cd local/
/usr/local/ -> cd etc/
/usr/local/etc/ -> cd openssl/
/usr/../etc/openssl/ -> cd private/
/usr/../../openssl/private/ ->
赠我空喜 2024-11-08 18:33:47

除了使用 PROMPT_DIRTRIM 的 bash 内置解决方案之外,您可能还想尝试 $(pwd | tail -c16),这比大多数其他答案简单一点,但只是给出当前目录的最后 16 个字符。当然,将 16 替换为您想要的任何数字。

Apart from the bash-builtin solution using PROMPT_DIRTRIM, you may want to try $(pwd | tail -c16), which is a tad simpler than most other answers, but just gives the last 16 characters of the current directory. Of course replace 16 by any number you want.

甜尕妞 2024-11-08 18:33:47

Raychi 的答案在 Mac / Catalina 上非常适合我。

将相应部分稍微修改为“两深”开头。

if (length($0) > 16 && NF > 5)
   print $1,$2,$3,".." NF-5 "..",$(NF-1),$NF

结果将类似于:

/Volumes/Work/..3../Python/Tutorials

我的 .bashrc 文件的相关部分作为独立的、复制并复制到文件中。粘贴解决方案是:

MYPSDIR_AWK=$(cat << 'EOF'
BEGIN { FS = OFS = "/" }
{
   sub(ENVIRON["HOME"], "~");
   if (length($0) > 16 && NF > 5)
      print $1,$2,$3,".." NF-5 "..",$(NF-1),$NF
   else
      print $0
}
EOF
)

export MYPSDIR='$(echo -n "$PWD" | awk "$MYPSDIR_AWK")'

请注意,上面不包括Raychi的着色方案。如果需要,请单独添加。

Raychi's answer works great for me on Mac / Catalina.

Modified the corresponding section slightly for a "two deep" beginning.

if (length($0) > 16 && NF > 5)
   print $1,$2,$3,".." NF-5 "..",$(NF-1),$NF

Result will be similar to:

/Volumes/Work/..3../Python/Tutorials

The related part of my .bashrc file as a self contained, copy & paste solution is:

MYPSDIR_AWK=$(cat << 'EOF'
BEGIN { FS = OFS = "/" }
{
   sub(ENVIRON["HOME"], "~");
   if (length($0) > 16 && NF > 5)
      print $1,$2,$3,".." NF-5 "..",$(NF-1),$NF
   else
      print $0
}
EOF
)

export MYPSDIR='$(echo -n "$PWD" | awk "$MYPSDIR_AWK")'

Note that the above does not include Raychi's colorization scheme. Add this separately if you need it.

寻梦旅人 2024-11-08 18:33:47

为什么不直接使用${string:position:length}
您可以执行 ${string:-$max_chars} 来获取字符串的最后一个 ${max_chars}

注意负值

Why not just use ${string:position:length}?
You can do ${string:-$max_chars} to have the last ${max_chars} of the string.

note the negative value

迷路的信 2024-11-08 18:33:47

与以前的解决方案没有太大不同。然而,也许更具可读性/可编辑性。不过,没有解决文件夹名称边界问题,只关注提示的长度。

### SET MY PROMPT ###
if [ -n "$PS1" ]; then
    # A temporary variable to contain our prompt command
    NEW_PROMPT_COMMAND='
        pwd_short=${PWD/#$HOME/\~};
        if [ ${#pwd_short} -gt 53 ]; then
            TRIMMED_PWD=${pwd_short: 0: 25}...${pwd_short: -25}
        else
            TRIMMED_PWD=${pwd_short}
        fi
    '

    # If there's an existing prompt command, let's not 
    # clobber it
    if [ -n "$PROMPT_COMMAND" ]; then
        PROMPT_COMMAND="$PROMPT_COMMAND;$NEW_PROMPT_COMMAND"
    else
        PROMPT_COMMAND="$NEW_PROMPT_COMMAND"
    fi

    # We're done with our temporary variable
    unset NEW_PROMPT_COMMAND

    # Set PS1 with our new variable
    # \h - hostname, \u - username
    PS1='\u@\h: $TRIMMED_PWD\$ '
fi

添加到 .bashrc 文件中。
提示的所有部分均已正确更新。如果您位于主目录中,第一部分会缩短。
示例:

user@computer: ~/misc/projs/solardrivers...src/com/mycompany/handles$

Not so different from previous solutions. However, maybe a bit more readable/editable. However, no solution to the folder name boundary, only focusing on the length of the prompt.

### SET MY PROMPT ###
if [ -n "$PS1" ]; then
    # A temporary variable to contain our prompt command
    NEW_PROMPT_COMMAND='
        pwd_short=${PWD/#$HOME/\~};
        if [ ${#pwd_short} -gt 53 ]; then
            TRIMMED_PWD=${pwd_short: 0: 25}...${pwd_short: -25}
        else
            TRIMMED_PWD=${pwd_short}
        fi
    '

    # If there's an existing prompt command, let's not 
    # clobber it
    if [ -n "$PROMPT_COMMAND" ]; then
        PROMPT_COMMAND="$PROMPT_COMMAND;$NEW_PROMPT_COMMAND"
    else
        PROMPT_COMMAND="$NEW_PROMPT_COMMAND"
    fi

    # We're done with our temporary variable
    unset NEW_PROMPT_COMMAND

    # Set PS1 with our new variable
    # \h - hostname, \u - username
    PS1='\u@\h: $TRIMMED_PWD\$ '
fi

added to the .bashrc file.
All parts of the prompt is updated properly. The first part is shortened if you're in your home directory.
Example:

user@computer: ~/misc/projs/solardrivers...src/com/mycompany/handles$

盗琴音 2024-11-08 18:33:47
generatePwd(){
  set -- "`pwd | sed -e s.${HOME}.~.g`"
  IFS="/"; declare -a array=($*)
  srt=""
  count=0
  for i in ${!array[@]}; do
      # echo ${array[i]} - $i/${#array[@]}
      if [[ $i == 0 ]]; then
        srt+=""
      elif [[ $i == $((${#array[@]}-1)) ]] || [[ $i == $((${#array[@]}-2)) ]]; then
          srt+="/${array[i]}"
      else
        count=$((${count}+1))
      fi
  done
  if [[ $count != 0 ]]; then
    srt="${array[0]}/.$count.$srt"
  else
    srt="${array[0]}$srt"
  fi
  echo "${srt}"
}

导出 PS1

PS1="\$(generatePwd)"

控制台

$ ~/.3./machine-learning/deep-learning-computer-vision
generatePwd(){
  set -- "`pwd | sed -e s.${HOME}.~.g`"
  IFS="/"; declare -a array=($*)
  srt=""
  count=0
  for i in ${!array[@]}; do
      # echo ${array[i]} - $i/${#array[@]}
      if [[ $i == 0 ]]; then
        srt+=""
      elif [[ $i == $((${#array[@]}-1)) ]] || [[ $i == $((${#array[@]}-2)) ]]; then
          srt+="/${array[i]}"
      else
        count=$((${count}+1))
      fi
  done
  if [[ $count != 0 ]]; then
    srt="${array[0]}/.$count.$srt"
  else
    srt="${array[0]}$srt"
  fi
  echo "${srt}"
}

export PS1

PS1="\$(generatePwd)"

Console

$ ~/.3./machine-learning/deep-learning-computer-vision
魔法唧唧 2024-11-08 18:33:47

https://github.com/chrissound/SodiumSierraStrawberry

允许您截断路径,例如:

来自:
/home/sodium/Projects/Personal/Sierra/Super/Long/Path/HolyAvacado

致:»项目/Sie…/Sup…/Lon…/Pat…/HolyAvacado/

https://github.com/chrissound/SodiumSierraStrawberry

Allows you to truncate a path like:

From:
/home/sodium/Projects/Personal/Sierra/Super/Long/Path/HolyAvacado

To: »Projects/Sie…/Sup…/Lon…/Pat…/HolyAvacado/

や三分注定 2024-11-08 18:33:47

我建议对我见过的一个小脚本进行改编:

function generate_pwd { 
pwd | awk -F/ 'BEGIN{ ORS="/" } END{for (i=1; i<=NF; i++){print substr($i,1,1)}}' 
}
export PS1="\$(generate_pwd) => "

您在 bashrc 中添加这几行,它可以正常工作:

/d/m/r/S/ => pwd
/d/montreui/rpmbuild/SOURCES

I suggest this adaptation of a small script I've seen :

function generate_pwd { 
pwd | awk -F/ 'BEGIN{ ORS="/" } END{for (i=1; i<=NF; i++){print substr($i,1,1)}}' 
}
export PS1="\$(generate_pwd) => "

You add these few lines in your bashrc and it works... normally :

/d/m/r/S/ => pwd
/d/montreui/rpmbuild/SOURCES
掩耳倾听 2024-11-08 18:33:47

我们得到了很好的答案。但我记得作为一个初学者我真的无法理解这一切。
对于想要更短版本的初学者:

例如:
更长路径

为您提供:
输入图片此处描述

如果你安装了 vscode code ~/.bashrc
查找此代码块,

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

将小写的 w 更改为大写的 W

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\W\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\W\$ '
fi
unset color_prompt force_color_prompt

这可确保仅打印工作目录的最后一个部分。保存并退出。

在终端中输入 source ~/.bashrc

试试

We got great answers. But I remember I really could not understand all that as a beginner.
For beginners who want a shorter version of the same:

For instance:
longer path

Gives you:
enter image description here

If you have vscode installed code ~/.bashrc
Look for this block of code

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

change the small w to capital W

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\W\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\W\$ '
fi
unset color_prompt force_color_prompt

This ensures that only the last component of the working directory is printed. Save and Exit.

In the terminal, enter source ~/.bashrc

Try it

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文