Thach Nguyen
Thach Nguyen

Reputation: 1

Passing an argument to an expression and get output from it?

I currently have the following script:

var_name=`cat X | grep Y`

where X and Y are a filename and some string. I want to make this general and turn X and Y into the first and the second argument passing for the script. I tried

var_name=`cat $1 | grep $2`

and

var_name=`cat "$1" | grep "$2"`

but neither works.

What is the correct way to do this?

Upvotes: 0

Views: 166

Answers (1)

hol
hol

Reputation: 8423

As suggested in the comments you may do a debug using bash -x to see what is going on. Also as mentioned the cat is not needed but still produces the result. Here is a short test. Maybe you revise your post and show your actual full program.

$>cat uuoc.sh
#!/bin/sh 
var_name=`cat "$1" | grep "$2"`
echo Result 1:
echo $var_name
var_name=`grep "$2" "$1"`
echo Result 2:
echo $var_name

$>cat myfile.txt
file 
with
pattern (1)
just
for
pattern (2)

$>./uuoc.sh myfile.txt pattern
Result 1:
pattern (1) pattern (2)
Result 2:
pattern (1) pattern (2)

Upvotes: 1

Related Questions