Bash - source内置命令和$HISTCMD变量

3
我遇到了bash 'source'内置命令的意外行为,与$HISTCMD环境变量的显示有关。
我有一个包含以下内容的'init_things'文件:
echo $HISTCMD

我在bash shell中输入以下内容:

$> echo $HISTCMD
100

$> cat init_things
echo $HISTCMD

$> source init_things
1

我原本期望最后一个命令将显示102。

我在zsh shell中尝试了它,它按预期显示了102。

有没有办法使bash的行为符合我的期望?(不需要在“init_things”中将HISTCMD值重置为1吗?)

为什么bash会表现出这样的行为?(我在bash手册中找不到答案)

这是否与bash的"互动性"有关?

bash版本:4.3

zsh版本:5.1


1
显然设置历史选项可以解决我的问题;在我的init_things文件中加入set -o history - Dominique Baldo
2
脚本默认不使用历史记录。 - jeremysprofile
好的。对于分叉的bash脚本来说,这似乎很自然,但对于被引用的脚本来说就不那么明显了,因为我们仍然在同一个bash进程中。感谢您的回答。 - Dominique Baldo
1个回答

0

我们对histcmd了解多少?

   HISTCMD
      The  history  number,  or  index in the history list, of the current
      command.  Assignments to HISTCMD are ignored.  If HISTCMD is  unset,
      it loses its special properties, even if it is subsequently reset.

我们还能从手册中学到哪些秘密呢?

   HISTCONTROL
      A  colon-separated list of values controlling how commands are saved
      on the history list.  If the list of  values  includes  ignorespace,
      lines  which  begin with a space character are not saved in the his‐
      tory list.  A value of ignoredups causes lines matching the previous
      history  entry  to not be saved.  A value of ignoreboth is shorthand
      for ignorespace and ignoredups.  A value  of  erasedups  causes  all
      previous lines matching the current line to be removed from the his‐
      tory list before that line is saved.  Any value  not  in  the  above
      list  is  ignored.   If  HISTCONTROL is unset, or does not include a
      valid value, all lines read by the shell parser  are  saved  on  the
      history  list,  subject  to the value of HISTIGNORE.  The second and
      subsequent lines of a multi-line compound command  are  not  tested,
      and are added to the history regardless of the value of HISTCONTROL.

具体来说:

ignoredups 的值会导致与上一个历史记录条目匹配的行不被保存。

这是问题的原因吗?也许是...

$ echo $HISTCONTROL 
ignoredups:

...但可能性不大。

我们能在最近的bash中复现这个问题吗?

$ source init_things 
7615
$ . init_things 
7616

不,其实不行。我们能在bash 4.3中重现吗?

$ . init_things 
1

是的!

CHANGELOG中有几行关于HISTCMD的说明,但都没有描述这个特定问题。我猜这只是在使用source时初始化HISTCMD时遇到的一个错误。


这只是其中一个 bug,我想。如果 bash 在这方面不完美,请跟踪历史记录。 - Ярослав Рахматуллин

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接