首页 > 解决方案 > 无法在 .sh 脚本中回显上次执行

问题描述

使用以下

cmd=$(uname -a)

printf "["!:0"]"

给我

[cmd1=Linux localhost.localdomain 2.6.32-300.10.1.el5uek #1 SMP Wed Feb 22 17:37:40 EST 2012 x86_64 x86_64 x86_64 GNU/Linux]

但是什么时候完成test.sh

#!/bin/bash
output=$(uname -a)


printf "["!:0"]"

我越来越

[!:0]

谢谢。

标签: bashscriptingshcommand-substitution

解决方案


如果您需要在 bash ( v4+) 脚本中执行上一个命令,

#!/bin/bash -i
# -i: interactive mode, enable history inside script
set -o history  # enable history, for old bash versions

cmd=$(uname -a)
history | sed -n 'x;${s/ *[0-9]\+ *\(\S*\)/\1/p}'  # print the line before last history entry after removing index

推荐阅读