编写一个接受多个多空间参数的bash脚本

(优秀的) Unix编程环境的例子考虑一个地址簿:

John Perkins 616-555-4444 Bill Jotto 773-222-1112 Dial-a-Clown 738-224-5823 Prince Alex 837-999-999 Pizza Hut 833-339-222 Pizza Puk 882-922-222 Pizza Buk 822-221-111 

现在我正在编写一个程序来search这个名为“ 411 ”的地址簿

  grep $* /file/location/411 

现在运行411将会屈服

  $> 411 John >John Perkins 616-555-4444 

现在说我想给约翰打个电话,邀请他做一些披萨(所以我在寻找约翰的数字和比萨的数字)。

  $>411 John Pizza grep: can't open pizza 

不匹配!

那么如何告诉shell使用任意空格接受多个参数呢?

当你用多于一个参数调用grep时,它假设第一个是模式,其他的都是要搜索的文件。 你需要做两个修改:

  1. 当你调用你的程序时,你需要用双引号括起来。 这是标准的shell行为。

  2. 您的程序将需要从命令行读取参数,并将它们分别发送到grep或构建复合表达式( arg1|arg2|arg3 ),并使用-E (扩展正则表达式)标志将其传递给grep

例如:

 args="$1" shift # $2 becomes $1, $3 becomes $2, and so on while [ -n "$1" ]; do args="$args|$1" shift done grep -E "$args" /path/to/address/book 

要么:

 while [ -n "$1" ]; do grep "$1" /path/to/address/book shift done