Using pipes within variables

Hi,

I'm trying avoid having a large number of 'if' statements in my script by setting up a variable within 'ksh' which can be expanded depending on parameters passed to the script. The output from the 'cat' command should be able pipe its output into any additional commands on the command line depending on the contents of the variable.

ie The code below should be able to list the complete file, only the executable lines, only the comment lines or be able to count the number of each type of line if required

extra_cmd=""

set -- $( getopt :ecl "$*" ) 

while [[ $1 != "--" ]] ; do
    case arg in
        "-e")  # Remove comments
                extra_cmd=" | grep -v \"^#\" " 
                ;;

        "-c") # Remove non comment lines
                extra_cmd=" | grep \"^#\" "
                ;;

         "-l")  # count lines
                extra_cmd="${extra_cmd} | wc -l "
                ;;

           *)  # Default
                extra_cmd=""           
                ;;
    esac
done
...
...
cat file ${extra_cmd}

However when this runs it displays the file on the screen rather than piping the output to 'grep' or 'wc' depending of the parameter passed to the script and then compains about the contents of the variable, which it takes as the name of another file to list

I have tried a variety of different ways of quoting the contents or escaping the '|' when setting up the variable but none are having the desired effect of piping the output from 'cat' into 'grep' or 'wc'.

Any help would be greatly appreciated

Stv T

Try:

eval cat file ${extra_cmd}

or

echo cat file1 $extra_cmd | sh
1 Like

Try :

eval cat file ${extra_cmd}

Jean-Pierre.

1 Like
case $arg in

Thanks for the replies - 'eval' gives me exactly what I was looking for

Stv T