0

I want to use ack-grep alias in .zshrc. Here is how my alias lookes like now:

alias 'ack'='ack-grep -C -i -G --match'

but what I need is to put strings from this:

% ack string1 string2

inside

alias 'ack'='ack-grep -C -i -G string1 --match string2'

How to make this?

Update

Here is the code that worked:

ack() { 
    case $# in
    1) args="$1";;
    2) args="$1 -G $2";;
    *) args="$@";;
    esac
    eval "ack-grep -iC $args"
}

In my case I need to use eval for using more than one variable.

Update 2

Updated code without security issues:

ack () {
    if (( $# == 2 )); then
        ack-grep -iC "$1" -G "$2"
    elif (( $# == 1 )); then
        ack-grep -iC "$1"
    else
        echo 'Sorry, function works only for one and two params. In other case use ack-grep. Reread .zshrc'
    fi
}
boldnik
  • 2,547
  • 2
  • 27
  • 32
  • Don't use `eval` unless you absolutely have to. And in this case, you don't. – chepner Feb 23 '13 at 00:28
  • Why I should not use `eval` ? – boldnik Feb 23 '13 at 15:16
  • It can be a security risk unless you have *absolute* control over the variables being expanded inside its argument, and it's making the shell do extra work instead of specifying exactly what you want the shell to do. – chepner Feb 23 '13 at 15:33

2 Answers2

0
Use a function:

ack() { ack-grep -C -i -G $1 --match $2; }

You will probably want to make it slightly more robust. Something like:

ack() { 
    case $# in
    1) args="-G $1";;
    2) args="-G $1 --match $2";;
    *) args="$@";;
    esac
    ack-grep -C -i "$args"
}

Aliases do not provide adequate functionality for this sort of thing, and functions should almost always be used instead. (In fact, you can omit "almost" from the preceding.)

William Pursell
  • 204,365
  • 48
  • 270
  • 300
0

eval is rarely necessary.

ack () { 
    if (( $# > 2 )); then
        ack-grep -iC "$@"
    else
        ack-grep -iC "$1" ${2:+-G "$2"}
    fi
}

Update: here is an exact version of your first solution, without eval.

ack() { 
    case $# in
    1) ack-grep -iC "$1";;
    2) ack-grep -iC "$1" -G "$2";;
    *) ack-grep -iC "$@";;
    esac
}
chepner
  • 497,756
  • 71
  • 530
  • 681
  • This function doesn't work because if I use `ack String` it works identical to `ack-grep -iC String`. But if you put `ack String String2` it outputs nothing, in difference to `ack-grep -iC String -G String2`. – boldnik Feb 23 '13 at 15:15
  • The code you posted in your update is different from the code in your original question and in William Pursell's answer (does `$1` go with `-G` or does it stand alone? Does `$2` go with `-G` or `--match`?) – chepner Feb 23 '13 at 15:38
  • Ok. The last version is really useful but it has restrictions. With `eval` I could use any other params if i need. But iif it can be a security issue, i'd use the updated code. – boldnik Feb 25 '13 at 09:16