Donnoughue
Donnoughue

Reputation: 43

How to pass a shell script argument as a variable to be used when executing grep command

I have a file called fruit.txt which contains a list of fruit names (apple, banana.orange,kiwi etc). I want to create a script that allows me to pass an argument when calling the script i.e. script.sh orange which will then search the file fruit.txt for the variable (orange) using grep. I have the following script...

script name and argument as follows: script.sh orange

script snippet as follows:

#!/bin/bash
nameFind=$1
echo `cat` "fruit.txt"|`grep` | $nameFind 

But I get the grep info usage command and it seems that the script is awaiting some additional command etc. Advice greatly appreciated.

Upvotes: 4

Views: 14304

Answers (2)

dramzy
dramzy

Reputation: 1429

The piping syntax is incorrect there. You are piping the output of grep as input to the variable named nameFind. So when the grep command tries to execute it is only getting the contents of fruit.txt. Do this instead:

#!/bin/bash
nameFind=$1
grep "$nameFind" fruit.txt

Upvotes: 5

Tom Fenech
Tom Fenech

Reputation: 74595

Something like this should work:

#!/bin/bash

name="$1"
grep "$name" fruit.txt

There's no need to use cat and grep together; you can simply pass the name of the file as the third argument, after the pattern to be matched. If you want to match fixed strings (i.e. no regular expressions), you can also use the -F modifier:

grep -F "$name" fruit.txt

Upvotes: 4

Related Questions