Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grep

bash

shell

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.

like image 980
Donnoughue Avatar asked Oct 15 '25 17:10

Donnoughue


1 Answers

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
like image 112
dramzy Avatar answered Oct 18 '25 10:10

dramzy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!