开发者

Join Arguments - Escape Spaces

Is there any easy way to "join" the arguments passed to a script? I'd like something similar to $@, but that passes the arguments at once.

For example, consider the following script:

$/bin/bash

./my_program $@

When called as

./script arg1 arg2 arg3

my_program will receive the arguments as 3 separated arguments. What I want, is to pass all the arguments a开发者_开发知识库s one argument, joining them — separated by spaces, something like calling:

./my_program arg1\ arg2\ arg3


Use this one:

./my_program "$*"


I've had a pretty similar problem today and came up with code like this (includes sanity checks):

#!/bin/sh

# sanity checks
if [ $# -lt 2 ]; then
    echo "USAGE  : $0 PATTERN1 [[PATTERN2] [...]]";
    echo "EXAMPLE: $0 TODO FIXME";
    exit 1;
fi

NEEDLE=$(echo $* | sed -s "s/ /\\\|/g")
grep $NEEDLE . -r --color=auto

This little script lets you search for various words recursively in all files below the current directory. You can use sed to replace your " " (space) delimiter with whatever you like. I replace a space with an escaped pipe: " " -> "\|" The resulting string can be parsed by grep.

Usage

Search for the terms "TODO" and "FIXME":

./script.sh TODO FIXME

You might wonder: Why not simply call grep directly?

grep "TODO\|FIXME" . -r

The answer is that I wanted to do some post-processing with the results in a more advanced script. Therefore I needed be able to compress all passed arguments (patterns) into a single string. And thats the key part here.

Konrad

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜