user425727
user425727

Reputation:

grep inside shell script not working

When I run this on the command line it works:

ls | grep -v "#$"

But when I do ls | scriptname and inside the script I have:

#fileformat=unix
#!/bin/bash
grep -iv '#$'

It's not working. Why?

[EDIT]

the reason for the first line is explained here.

besides that even if i remove the first two lines it SHOULD work. i tried the exact same on a remote Solaris account and it did work. so is it my Fedora installation?

Upvotes: 2

Views: 7789

Answers (3)

shellter
shellter

Reputation: 37248

1st off you need #! /bin/bash as the first line in your script.

Then '#$' has no meaning in the shell pantheon of parameters. Are you searching for a '#' at the end of the line? (That is OK). But if you meant '$#' but then $# is the parameter that means the 'number of arguments on the command-line'

Generally, piping a list of files to a script to acted on would have to be accomplished with further wrapper. So a bare-bones, general solution to the problem you pose might be :

$cat scriptname
#!/bin/bash

while read fileTargs ; do
   grep -iv "${@}" ${fileTargs}   # (search targets).
done

called as

ls | scriptname srchTargets

I hope this helps.

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361546

The hash-bang line needs to be the first line in the script. Get rid of the #fileformat=unix. Also make sure your script is executable (chmod +x scriptname). This works:

#!/bin/bash
grep -iv '#$'

Upvotes: 2

ljkyser
ljkyser

Reputation: 1019

Change it to ls < scriptname so that the output is passed to ls.

Upvotes: 0

Related Questions