【问题标题】:printing output of command history 1 from shell script从 shell 脚本打印命令历史 1 的输出
【发布时间】:2018-07-29 08:36:57
【问题描述】:

这是我的问题,如果我在控制台输入以下内容,

var=`history 1`
echo $var

我得到了想要的输出。但是当我在 shell 脚本中做同样的事情时,它没有显示任何输出。此外,对于 pwdls 等其他命令,脚本会毫无问题地显示所需的输出。

【问题讨论】:

  • var=history 1 即 backquotehistorybackquote
  • 我假设history 命令只适用于交互式shell。
  • #!/bin/bash 替换为#!/bin/bash -i
  • 显示输出,但输出不符合预期....即不显示最后输入的命令。
  • 您想要来自 进程的history,即启动此脚本的交互式会话吗?

标签: bash shell variables history


【解决方案1】:

由于变量的值包含空格,请在其周围加上引号。

例如:

var='history 1'
echo $var

【讨论】:

  • 我希望从 shell 脚本#history 1 打印下面的输出
  • 您可以将此代码复制粘贴到您的 shell 脚本中,它会起作用。
  • #./test.sh output is --> history 3 #cat test.sh #!/bin/bash var='history 3' echo $var EXPECTED 如下,#history 3 404 2018-02-19 12:16:08 ./test.sh 405 2018-02-19 12:16:10 cat test.sh 406 2018-02-19 12:16:14 历史 3
【解决方案2】:

我相信您所需要的只是如下:

1- 询问用户需要在脚本中打印history 的号码。

2- 运行脚本并从用户那里获取输入并得到如下输出:

cat get_history.ksh
echo "Enter the line number of history which you want to get.."
read number

if [[ $# -eq 0 ]]
then
        echo "Usage of script: get_history.ksh number_of_lines"
        exit
else
        history "$number"
fi

添加了逻辑,如果传递的参数数量为 0,它将检查参数,然后它将退出脚本。

【讨论】:

    【解决方案3】:

    默认history在脚本中是关闭的,所以你需要打开它:

    set -o history
    var=$(history 1)
    echo "$var"
    

    请注意$( ) 的首选用法,而不是已弃用的反引号。

    不过,这只会查看当前进程的历史,也就是这个shell脚本,所以它是相当没用的。

    【讨论】:

      猜你喜欢
      • 2013-08-21
      • 1970-01-01
      • 2012-01-25
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 2021-07-31
      相关资源
      最近更新 更多