search
HomeOperation and MaintenanceNginxEight mysterious uses of the '!' operator in Linux commands

In different shells, the usage of most Linux commands using the '!' symbol may vary. While the examples I provide are typically used in bash shells, some other Linux shells may have different implementations or may not support certain uses of the '!' symbol at all.

Let’s dive into the surprising and mysterious uses of the ‘!’ symbol in Linux commands.

Linux 命令中“!”操作符的八个神秘用途

1. Use the command number to run a command from the history

A useful tip is that you can run a command from a previously executed Find the historical command in the command and run it again. First, find the number of the command by running the 'history' command.

linuxmi@linuxmi:~/www.linuxmi.com$ history

Linux 命令中“!”操作符的八个神秘用途

Find recently executed commands in Linux

To run a command from history by command number, you can use the '!' symbol followed by the command number ,As follows.

$ !58

Linux 命令中“!”操作符的八个神秘用途

Run command by command number

When you execute the above command, it will run the command at line 58 in the history.

Please note that the actual command number may vary depending on your command history. You can use the history command to view a list of commands and their line numbers.

2. Run previously executed commands in Linux

You can run previously executed commands in the order in which they are run. The last command run will be expressed as -1, the second to last is -2, the seventh to last is -7, and so on. You can use !-n, where n is the reciprocal number of the command you want to quote. As shown below

$ history$ !-3$ !-6$ !-10

Linux 命令中“!”操作符的八个神秘用途

Rerun the command in Linux

3. Pass the parameters of the previous command to the new command

I needed to list the contents of the directory '/home/linuxmi/snap', so I executed the following command:

$ ls /home/linuxmi/snap

Then I realized that I should run the "ls -l" command to see which files Executable. Instead of retyping the entire command, just pass the parameters of the previous command to this new command, like this:

$ ls -l !$

Linux 命令中“!”操作符的八个神秘用途

Here, '!$' will be The parameters passed in the previous command are passed to this new command.

4. How to handle two or more parameters in the command

Suppose I create a text file named 1.txt on the desktop.

linuxmi@linuxmi ~/www.linuxmi.com% touch /home/linuxmi/linuxmi.go

Then copy it to the '/home/avi/Downloads' directory using the full path, using the cp command.

linuxmi@linuxmi ~/www.linuxmi.com% cp /home/linuxmi/linuxmi.go /home/linuxmi/go

Now we pass two parameters in the cp command. The first one is '/home/avi/Desktop/1.txt' and the second one is '/home/avi/Downloads'. We can print two parameters in different ways by executing the echo command and using different parameters.

linuxmi@linuxmi ~/www.linuxmi.com% echo "第一个参数是:!^"echo "第一个参数是:/home/linuxmi/linuxmi.go"第一个参数是:/home/linuxmi/linuxmi.golinuxmi@linuxmi ~/www.linuxmi.com% echo "第二个参数是:!cp:2"echo "第二个参数是:/home/linuxmi/go"第二个参数是:/home/linuxmi/go

Please note that the first parameter can be displayed as "!^", while other parameters can be printed by executing "![Command Name]:[Parameter Number]".

In the above example, the first command is 'cp' and the second parameter needs to be printed. Hence "!cp:2". For the xyz command with 5 parameters, if you need to get the 4th parameter, you can use "!xyz:4" and use that parameter as needed. All parameters can be accessed via "!*".

Linux 命令中“!”操作符的八个神秘用途

Processing two or more parameters

5. Run the latest command based on specific keywords

We can execute recently executed commands based on keywords. The details are as follows:

$ ls /home > /dev/null				[Command 1]$ ls -l /home/linuxmi/linuxmi > /dev/null		[Command 2]	$ ls -la /home/linuxmi/linuxmi.com > /dev/null	[Command 3]$ ls -lA /usr/bin > /dev/null			[Command 4]

Here we use the ls command, but with different options and different folders. Also, to keep the console clean, we will send the output of each command to "/dev/null".

Now execute the last executed command based on the keyword:

$ ! ls			[Command 1]$ ! ls -l		[Command 2]	$ ! ls -la		[Command 3]$ ! ls -lA		[Command 4]

Linux 命令中“!”操作符的八个神秘用途

检查输出,你会惊讶地发现你正在运行已经执行过的命令,只是使用了ls关键词。

6、在Linux中重复上次执行的命令

你可以使用(!!)操作符来运行/修改你上次执行的命令,这是一个简写符号,允许你引用在命令行中执行的上一个命令。

例如,我运行了一个单行脚本来查找Linux机器的IP地址:

$ ip addr show | grep inet | grep -v 'inet6'| grep -v '127.0.0.1' | awk '{print $2}' | cut -f1 -d/

然后突然我发现我需要将上述脚本的输出重定向到一个名为ip.txt的文件中,那么我该怎么办呢?我需要重新输入整个命令并将输出重定向到文件吗?好吧,一个简单的解决方案是使用上箭头键来调出上一条命令,并在末尾添加’> ip.txt’来将输出重定向到文件。

$ ip addr show | grep inet | grep -v 'inet6'| grep -v '127.0.0.1' | awk '{print $2}' | cut -f1 -d/ > ip.txt

感谢上箭头键的救命作用。现在考虑以下情况,下次我运行下面的单行脚本。

ifconfig | grep "inet addr:" | awk '{print $2}' | grep -v '127.0.0.1' | cut -f2 -d:

当我运行脚本时,bash提示返回了一个错误,信息为“bash: ifconfig: command not found”,我很容易猜到我以一个普通用户的身份运行了这个命令,而它应该以root身份运行。

那么解决办法是什么呢?登录为root然后重新输入整个命令是很困难的!在上一个示例中的(上箭头键)在这里也无法帮助。所以,要调用用户的最后一个命令,需要输入“!!”(不需要引号)

su -c “!!” root

这里的su是切换用户的命令,root是要切换到的用户,-c是以指定的用户身份运行命令的选项,最重要的部分是!!将被替换为上次运行的命令。是的!你需要提供root密码。

7、使用’!’操作符删除除一个文件之外的所有文件

在Linux中,’!’操作符(也称为”bang”操作符)用于历史扩展,它允许你引用先前的命令并对其执行各种操作。要从目录中删除除了特定文件(important_file.txt)之外的所有文件,可以使用带有’!’操作符的rm命令,如下所示。

$ rm !(important_file.txt)

要从文件夹中删除除了扩展名为’.pdf’之外的所有文件类型。

$ $ rm !(*.pdf)

8、检查Linux中的目录是否存在

在这里,我们将使用’! -d’来验证目录是否存在,如果目录不存在,则紧随其后的是逻辑与操作符(&&),打印出目录不存在,如果目录存在,则紧随其后的是逻辑或操作符(||),打印出目录存在。

逻辑是,当[ ! -d /home/linuxmi/linuxmi.com ]的输出为0时,它将执行逻辑与之后的内容,否则它将转到逻辑或(||)并执行逻辑或之后的内容。

$ [ ! -d /home/linuxmi/linuxmi.com ] && printf '\nno such /home/linuxmi/linuxmi.com directory exist\n' || printf '\n/home/linuxmi/linuxmi.com directory exist\n'

类似于上面的条件,但是如果所需目录不存在,它将退出命令。

$ [ ! -d /home/linuxmi/linuxmi.com] && exit

在脚本语言中的一般实现,如果所需目录不存在,它将创建一个目录。

[ ! -d /home/linuxmi/linuxmi.com] && mkdir /home/linuxmi/linuxmi.com

The above is the detailed content of Eight mysterious uses of the '!' operator in Linux commands. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
Musk boldly predicts that AI will surpass humans in all respects by 2030!Musk boldly predicts that AI will surpass humans in all respects by 2030!Apr 13, 2025 pm 11:03 PM

Elon Musk recently made bold predictions on the future development of artificial intelligence (AI) on social platforms. He pointed out that AI technology is developing at an unprecedented rate, while humans' understanding of this is relatively lagging behind. Musk predicts that by the end of 2025, the intelligence level of AI will exceed any single human being; between 2027 and 2028, the overall intelligence of AI will surpass all human beings. Musk further stressed that the trend of AI surpassing human intelligence will become increasingly significant and is expected to be close to 100% by 2030. This indicates the arrival of a new era in which AI completely surpasses human intelligence. The emergence of ChatGPT has triggered a global investment boom in the field of artificial intelligence. CBInsights data shows risk last year

Japanese automakers began to save themselves! Honda and Nissan announced the start of merger negotiationsJapanese automakers began to save themselves! Honda and Nissan announced the start of merger negotiationsApr 13, 2025 pm 11:00 PM

Nissan, Honda and Mitsubishi Motors work together to explore the new future of the automotive industry! Today, the three companies signed a memorandum of understanding, and Honda and Nissan officially launched business merger negotiations, with the goal of reaching an agreement in June next year. Mitsubishi Motors will also evaluate the possibility of joining the merger. Honda and Nissan plan to establish a holding company in August 2026, and are expected to complete negotiations by June 2025. The shares of the two companies will be delisted from the end of July to August 2026. The president of the holding company will be appointed by Honda, and most of the directors will be appointed by Honda. The collaboration aims to explore the potential ways Mitsubishi Motors can engage in the integration of Nissan and Honda and share synergies. The three companies have reached a preliminary agreement to focus on strategic cooperation in the fields of intelligence and electrification, and Mitsubishi Motors will participate.

Google releases the most powerful model in history, 'Gemini 2.0'! Performance improvementGoogle releases the most powerful model in history, 'Gemini 2.0'! Performance improvementApr 13, 2025 pm 10:57 PM

Google launches Gemini2.0: The new generation of AI models leads the era of intelligent bodies! Today (December 12), Google officially released its latest and most powerful AI model - Gemini2.0, aiming to lay the foundation for the new era of agents. The model has achieved significant improvements in performance, multimodal capabilities, and native tool applications. Gemini2.0 performed well in key benchmarks, twice as fast as the previous generation Gemini1.5Pro. It supports multimodal input and output such as images, videos, and audio, such as native text images and customizable multilingual text-to-speech (TTS). In addition, Gemini2.0 restore supports Google search, code execution and customization of third-party users

Honor Internet Service: AI empowerment and experience improvement, turning technological imagination into a concrete image of lifeHonor Internet Service: AI empowerment and experience improvement, turning technological imagination into a concrete image of lifeApr 13, 2025 pm 10:54 PM

On December 19, a media communication meeting with Honor Internet Services with the theme of "New Ecology, New Potential Energy and New Growth" was held in Guangzhou. Sun Jianfa, director of Honor Consumer Cloud Business Department, Ren Xulong, director of Guangdong Honor Business Department, Wang Guan, director of Honor Cloud business rules and marketing, and Su Tong, director of Guangdong Honor Retail, attended the meeting and shared the development strategy of Honor Internet services, such as AI, and other technological innovations and high-quality experiences. Honor Internet Services have been newly advanced, creating a more complete Internet service ecosystem. Honor Internet Services provide full-scene Internet service experience to Honor global terminal users, empowering users to "enjoy a smarter and more high-quality digital life" with a diverse product matrix in one-stop and full link. Sun Jianfa said, "Rong

Technology empowers smart medical care! Intel joins hands with industry partners to explore the way of integration of medicine and healthTechnology empowers smart medical care! Intel joins hands with industry partners to explore the way of integration of medicine and healthApr 13, 2025 pm 10:51 PM

Empowering technology to benefit people's livelihood: the new chapter of smart medical care is reduced to make "small illnesses not leaving townships" a reality. From remote consultation to AI-assisted diagnosis, technological advances are reshaping the medical service model. This article will discuss the results of the 2024 Intel Smart Medical Health Cooperation Forum, showing how intelligent technology can improve medical efficiency and convenience. Song Jiqiang, vice president of Intel Research Institute and dean of Intel China Research Institute of 2024 Intel Intel Intelligent Medical and Health Cooperation Forum, pointed out that strong computing power is the core driving force for the development of the digital economy and is also driving innovation in the medical and health field. Intel is committed to providing high-performance computing to meet the diverse needs of high concurrency, high precision and low latency in the medical field, and build large-scale intelligent medical solutions. Intel Research

No.9 Company exclusively named Yi Yang Qianxi's Bath Pool Concert: Showing the Art of Rejuvenating the BrandNo.9 Company exclusively named Yi Yang Qianxi's Bath Pool Concert: Showing the Art of Rejuvenating the BrandApr 13, 2025 pm 10:48 PM

Nine Company and brand spokesperson Yi Yang Qianxi have created glory again in the third year of cooperation! The "Battle Pond" Bath Pond Concert, exclusively sponsored by No. 9, has set a new benchmark for brand rejuvenation and industry cross-border cooperation with its unique artistic expression and sincere emotional expression. This concert, which was launched on December 7 and 8, is not only another innovative attempt in cross-border marketing by No. 9, but also a successful example of the deep emotional connection between the brand and young users. The blend of music and life: The unique charm of the bath pool concert. As the exclusive title party of the bath pool concert of "By the Pond", No. 9 has worked hard to create a unique music experience. The concert is divided into two episodes, which will be broadcast on December 7 and 8 respectively. Taking the "bath pool" as a scene with a very lifelike atmosphere

Cryptocurrency shakes again! More than 100,000 people have lost their positions, with a total amount of over 400 million US dollarsCryptocurrency shakes again! More than 100,000 people have lost their positions, with a total amount of over 400 million US dollarsApr 13, 2025 pm 10:45 PM

During the trading session of the US stock market, the price of Bitcoin exceeded US$107,000, setting a record high! As of now, the price has fallen slightly, maintaining around US$106,000. Coinglass data shows that in the past 24 hours, the number of people in the cryptocurrency market has reached 113,000, with a total amount of up to US$423 million. Among them, the long positions were liquidated by US$197 million and the short positions were liquidated by US$226 million. Affected by this, cryptocurrency concept stocks have generally risen. RiotPlatforms shares rose more than 8%, Bitdeer Technologies rose more than 10%, Canaan Technology rose more than 8%, and Coinbase shares rose 1.52%.

Lei Jun talks about Xiaomi's future goals: build at least 20 world-class factories in 10 years!Lei Jun talks about Xiaomi's future goals: build at least 20 world-class factories in 10 years!Apr 13, 2025 pm 10:42 PM

Xiaomi New Year's Eve Live: Lei Jun revealed that at least 20 world-class factories will be built in the next ten years! During last night's New Year's Eve live broadcast, Xiaomi Chairman Lei Jun summarized the company's brilliant achievements in the past year and announced that in the next ten years, Xiaomi plans to build at least 20 world-class factories! At present, Xiaomi has three advanced production bases: the mobile phone manufacturing center in Changping, Beijing’s modern electric vehicle factory in Yizhuang, and the Wuhan Smart Home Appliances Industrial Park, which will be put into production the year after tomorrow. These factories not only represent the peak of advanced manufacturing technology, but also show Xiaomi's huge contribution to the upgrading of China's manufacturing industry. Faced with Xiaomi's increasingly expanding business territory, Lei Jun emphasized that this is just the beginning. Xiaomi will make every effort to promote its intelligent manufacturing strategy, and in the future, more high-standard factories will be completed and put into production.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools