-1

I am writing an Ubuntu bash script that will be used in a generic form. I want to find out whether it is possible to pass a multiple commands in a piped fashion. This is what I am trying to achive:

#!/bin/bash
cat $1 | $2 | while read line
do
    # do something
done

The script is to be run like this:

./myscript.sh data.txt "grep status | grep Approved"

Is this possible to be achived. I had a go, but only got far as:

./myscript.sh data.txt "grep status"

This worked.

Is this is possible? I can reuse this script to pass in different commands to do different things but each having common code i.e. myscript.sh.

When the the do something is replaced by:

echo $2

This does display what was typed in to the second argument.

Rajiv Jain
  • 13
  • 1
  • 5

1 Answers1

0

The problem is that | must be literally present in the command line to be interpreted as the control operator. As a result of a variable expansion, it's interpreted as the string |, i.e. as if you entered '|' on the command line.

You can use eval to let the shell interpret the variable as a new pipeline or command list. It opens another can of worms, though - you might need to introduce another level of quoting and you need to be careful not to run into security issues.

pipeline='grep a | grep b'
echo a b c | eval "$pipeline"
choroba
  • 231,213
  • 25
  • 204
  • 289