使用“!"在脚本中执行具有相同参数的命令 [英] use "!" to execute commands with same parameter in a script

查看:25
本文介绍了使用“!"在脚本中执行具有相同参数的命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 shell 中,我运行以下命令没有问题,

In a shell, I run following commands without problem,

ls -al

!ls

ls 的第二次调用也会列出带有 -al 标志的文件.但是,当我把上面的脚本放到 bash 脚本中时,就会抛出抱怨,

the second invocation to ls also list files with -al flag. However, when I put the above script to a bash script, complaints are thrown,

!ls,未找到命令.

如何在脚本中实现同样的效果?

how to realise the same effects in script?

推荐答案

您需要在脚本中同时打开命令历史记录和 !-style 历史记录扩展(在非交互式 shell 中默认情况下这两个都是关闭的):

You would need to turn on both command history and !-style history expansion in your script (both are off by default in non-interactive shells):

set -o history
set -o histexpand

扩展的命令也会回显到标准错误,就像在交互式 shell 中一样.您可以通过打开 histverify shell 选项 (shopt -s histverify) 来防止这种情况发生,但在非交互式 shell 中,这似乎使历史扩展为空-操作.

The expanded command is also echoed to standard error, just like in an interactive shell. You can prevent that by turning on the histverify shell option (shopt -s histverify), but in a non-interactive shell, that seems to make the history expansion a null-op.

这篇关于使用“!"在脚本中执行具有相同参数的命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆