0

I have the following snippet:

#!/bin/bash

OPTIND=1
while getopts ":m:t" params; do
    case "${params}" in

        m)
             bar=$OPTARG ;;
        t)
            foo=$OPTARG ;;

        \?) 
            "Invalid option: -$OPTARG" >&2
            print_usage 
            exit 2
            ;;

        :)
            echo "Option -$OPTARG requires an argument." >&2
            print_usage
            exit 2
            ;;

        esac

done
shift "$(( OPTIND-1 ))"
echo "${foo}"  && echo  "${bar}"

How can I output the stdout using pipes through this script?

For example:

echo "this is the test" | bash getoptscript.sh -m - 

And it should provide : this is the test as the output.

2
  • Found the answer. Something like: echo "Test" | xargs bash getoptscript.sh -m . But is this "good" way? Commented Jun 28, 2017 at 12:36
  • So, you want the script to read stdin if the argument to the switch is a dash - and otherwise use the argument itself? That should be a simple test within the m) case, read from stdin if OPTARG is -, otherwise use OPTARG itself. I'm not exactly sure if this is what you wanted, though. It would seem more common to have dash as a filename representing stdin. Some commands have a different option characters for giving the literal value and for giving a reference to a file from which to read it Commented Jun 28, 2017 at 12:40

2 Answers 2

1

Rather than taking the string as a command line argument, you may simply use cat to read the script's standard input:

printf '%s\n' "$foo"
if [ "$bar" = "-" ]; then
    # assume data is on standard input
    cat
else
    print '%s\n' "$bar"
fi
0

By piping the output to xargs, which converts its input into arguments:

echo "this is the test" | xargs bash getoptscript.sh -m - 

Which will result in:

bash getoptscript.sh -m - this is the test

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.