开源软件的一大优势是源代码是开放的 :-)
Bash 本身不提供此功能,但您可以使用各种技巧来提供子集(例如替换\u
为$USER
等)。但是,这需要大量重复功能,并确保代码与bash
将来的任何操作保持同步。
如果您想获得提示变量的所有功能(并且您不介意通过一些编码弄脏您的手(并且,如果您介意,您为什么在这里?)),添加到壳本身。
如果您下载bash
(我正在查看版本 4.2)的代码,则有一个y.tab.c
包含该decode_prompt_string()
函数的文件:
char *decode_prompt_string (string) char *string; { ... }
这是评估PSx
提示变量的函数。为了允许向 shell 本身的用户提供此功能(而不仅仅是由shell 使用),您可以按照以下步骤添加内部命令evalps1
。
首先,进行更改,support/mkversion.sh
以免您将其与“真实”混淆bash
,并且 FSF 可以出于保修目的否认所有知识 :-) 只需更改一行(我添加了-pax
一点):
echo "#define DISTVERSION \"${float_dist}-pax\""
二、更改builtins/Makefile.in
添加新的源文件。这需要许多步骤。
(a) 添加$(srcdir)/evalps1.def
到DEFSRC
.
(b) 添加evalps1.o
到OFILES
.
(c) 添加所需的依赖项:
evalps1.o: evalps1.def $(topdir)/bashtypes.h $(topdir)/config.h \
$(topdir)/bashintl.h $(topdir)/shell.h common.h
第三,添加builtins/evalps1.def
文件本身,这是运行evalps1
命令时执行的代码:
This file is evalps1.def, from which is created evalps1.c.
It implements the builtin "evalps1" in Bash.
Copyright (C) 1987-2009 Free Software Foundation, Inc.
This file is part of GNU Bash, the Bourne Again SHell.
Bash is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Bash is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Bash. If not, see <http://www.gnu.org/licenses/>.
$PRODUCES evalps1.c
$BUILTIN evalps1
$FUNCTION evalps1_builtin
$SHORT_DOC evalps1
Outputs the fully interpreted PS1 prompt.
Outputs the PS1 prompt, fully evaluated, for whatever nefarious purposes
you require.
$END
#include <config.h>
#include "../bashtypes.h"
#include <stdio.h>
#include "../bashintl.h"
#include "../shell.h"
#include "common.h"
int
evalps1_builtin (list)
WORD_LIST *list;
{
char *ps1 = get_string_value ("PS1");
if (ps1 != 0)
{
ps1 = decode_prompt_string (ps1);
if (ps1 != 0)
{
printf ("%s", ps1);
}
}
return 0;
}
其中大部分是 GPL 许可证(因为我从 修改它exit.def
),最后有一个非常简单的函数来获取和解码PS1
。
最后,只需在顶级目录中构建东西:
./configure
make
出现的bash
可执行文件可以重命名为paxsh
,尽管我怀疑它是否会像它的祖先一样流行:-)
运行它,你可以看到它的实际效果:
pax> mv bash paxsh
pax> ./paxsh --version
GNU bash, version 4.2-pax.0(1)-release (i686-pc-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
pax> ./paxsh
pax> echo $BASH_VERSION
4.2-pax.0(1)-release
pax> echo "[$PS1]"
[pax> ]
pax> echo "[$(evalps1)]"
[pax> ]
pax> PS1="\h: "
paxbox01: echo "[$PS1]"
[\h: ]
paxbox01: echo "[$(evalps1)]"
[paxbox01: ]
当您将其中一个PSx
变量放入提示符时,回显$PS1
只是为您提供变量,而evalps1
命令对其进行评估并输出结果。
现在,当然,对代码进行更改以bash
添加内部命令可能会被某些人认为是矫枉过正,但是,如果您想要对 进行完美评估PS1
,这当然是一种选择。