如何在提示符中显示目录?

如何在提示符中显示目录?

如何在提示符中的 $ 之前显示目录?在此输入图像描述

答案1

bash 手册页有一个转义序列列表,您可以将其放入提示中,以便 shell 展开它们。查看“提示”,您会发现此表:

          \a     an ASCII bell character (07)
          \d     the date in "Weekday Month Date" format (e.g., "Tue May 26")
          \D{format}
                 the  format is passed to strftime(3) and the result is inserted into the
                 prompt string; an empty format results in a locale-specific time  repre‐
                 sentation.  The braces are required
          \e     an ASCII escape character (033)
          \h     the hostname up to the first `.'
          \H     the hostname
          \j     the number of jobs currently managed by the shell
          \l     the basename of the shell's terminal device name
          \n     newline
          \r     carriage return
          \s     the  name  of  the  shell, the basename of $0 (the portion following the
                 final slash)
          \t     the current time in 24-hour HH:MM:SS format
          \T     the current time in 12-hour HH:MM:SS format
          \@     the current time in 12-hour am/pm format
          \A     the current time in 24-hour HH:MM format
          \u     the username of the current user
          \v     the version of bash (e.g., 2.00)
          \V     the release of bash, version + patch level (e.g., 2.00.0)
          \w     the current working directory, with $HOME abbreviated with a tilde (uses
                 the value of the PROMPT_DIRTRIM variable)
          \W     the  basename  of  the current working directory, with $HOME abbreviated
                 with a tilde
          \!     the history number of this command
          \#     the command number of this command
          \$     if the effective UID is 0, a #, otherwise a $
          \nnn   the character corresponding to the octal number nnn
          \\     a backslash
          \[     begin a sequence of non-printing characters,  which  could  be  used  to
                 embed a terminal control sequence into the prompt
          \]     end a sequence of non-printing characters

你想要的是 \w,所以就这样做

PS1="\w $ "

这会将其更改为当前 shell。您可以将定义放入 .profile 中以使其保持不变。

答案2

所有执行此操作的方法都是非标准的,因此请小心并仅针对单个 shell 进行设置。

一般来说,有两种方法可以实现所需的行为:

使用转义序列

用户 Nick 已针对 bash 描述了此方法。这取决于 bash 扩展。该标准仅要求PS1应该进行参数扩展(即shell变量扩展)并且shell应该扩展“!”由历史命令编号(请注意,标准不描述“\!”,而是单个感叹号。

使用命令替换

此方法通常由 ksh 用户使用,但有意不成为标准的一部分,因为它存在安全风险。该标准不要求 shell 忽略导入的PS1环境,因此该环境可能包含来自坏人的攻击命令。

该标准的未来版本很可能会标准化命令替换,PS1但随后要么要求 shell 忽略导入的PS1环境,要么打开 shell 的命令替换并在打开后设置命令才能工作。

相关内容