Unix script 12 - extrnal programs 外部程序

本文介绍如何在Shell脚本中使用Backtick来执行外部命令,并捕获其输出,通过具体示例展示了如何利用该特性提高脚本效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

External programs are often used within shell scripts; there are a fewbuiltin commands (echo,which, and testare commonly builtin), but many useful commands are actually Unix utilities,such astr, grep, expr and cut.

The backtick (`)is also often associated with external commands. Because of this, we will discuss the backtick first.
The backtick is used to indicate that the enclosed text is to be executedas a command. This is quite simple to understand. First, use aninteractive shell to read your full name from/etc/passwd:

$ grep "^${USER}:" /etc/passwd | cut -d: -f5
Steve Parker

Now we will grab this output into a variable which we can manipulate more easily:

$ MYNAME=`grep "^${USER}:" /etc/passwd | cut -d: -f5`
$ echo $MYNAME
Steve Parker

So we see that the backtick simply catches the standard output from anycommand or set of commands we choose to run. It can also improve performanceif you want to run a slow command or set of commands and parse various bits of its output:


#!/bin/sh
find / -name "*.html" -print | grep "/index.html$"
find / -name "*.html" -print | grep "/contents.html$"

This code could take a long time to run, and we are doing it twice!
A better solution is:


#!/bin/sh
HTML_FILES=`find / -name "*.html" -print`
echo "$HTML_FILES" | grep "/index.html$"
echo "$HTML_FILES" | grep "/contents.html$"
Note: the quotes around $HTML_FILES are essential to preserve the newlines between each file listed. Otherwise, grep will see one huge long line of text, and not one line per file.

This way, we are only running the slow find once, roughlyhalving the execution time of the script.

We discuss specific examples further in the Hints and Tips section of this tutorial.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值