1

My bash script looks like this:

#!/bin/bash
grep -r --color=always $@ . | nolong

The file is saved in /usr/bin/findstr

Everything's ok when I run this:

findstr hello

But when I run this:

findstr hello world

It searches only for hello.

Question: How can I put $@ in quotes, so that it would understand it is a single parameter?

2 Answers2

7

If you want to search for the regexp that is the concatenation of the arguments with space characters in between, that would be:

#! /bin/sh -
IFS=' ' # used for "$*"
grep -r --color=always -e "$*" . | nolong

"$*" joins the positional parameters with the first character (actually byte except with yash) of $IFS.

Note (as you seem to be confused by the meaning of space) that if you run:

myscript hello world
myscript hello  world
myscript 'hello'   "world"

The spaces (or quotes) are not passed to myscript, they are just part of the shell command-line syntax. In those 3 shell command lines, myscript receives the same 3 arguments: "myscript", "hello" and "world".

If you want to search for any of the regexps passed as arguments:

#! /bin/sh -
for i do
  set -- "$@" -e "$i"
  shift
done
[ "$#" -gt 0 ] && grep -r --color=always "$@" . | nolong
  • myscript receives the argument "myscript", are you sure about that? – Aaron Franke Feb 13 '19 at 01:32
  • @AaronFranke, the script will be invoked as with the execve("/path/to/myscript", ["myscript", "hello", "world"], environ) system call (myscript is argv[0] at that point). Which because of the she-bang will become execve("/bin/sh", ["/bin/sh" or "myscript", "/path/to/myscript", "hello", "world"]) and sh will make $0 /path/to/myscript, and the original myscript argv[0] will be lost (to the script at least). – Stéphane Chazelas Feb 17 '19 at 15:00
0

You need to quote the argument when your script is called to show that it is one argument and not two independent arguments. Inside your script you then have to use "$@".

grep -r --color=always "$@" . | nolong

And the call is (for example)...

findstr "hello world"

(But note that the grep pattern uses just one argument, so "$1" instead of "$@" would have sufficed.)

Janis
  • 14,222
  • Thanks. How can I make it to work without quotes when I use findstr? I.e. findstr hello world instead of findstr "hello world" – KEKC_leader Mar 13 '15 at 12:37
  • 1
    This is a case where you would want "$*" instead of "$@" -- you want to pass a single argument to grep. – glenn jackman Mar 13 '15 at 13:15