-2

I have the following script:

#!/bin/sh

[ "${#}" -eq "0" ] && (printf "%s\\n" "${0}: word ..." >&2; exit 1)

_whats()
{
    [ -z "${1}" ] && return 1
    [ -z "${2}" ] && more_than_one="1"

    for word; do
        response="$(dig +short txt ${word}.wp.dg.cx)"
        printf "%s\\n" "${response}"
        if [ -z "${more_than_one}" ]; then
            printf "\\n%s\\n\\n" ":::::::::::::::::::::::::::::::::::::::::"
        fi
    done
}

_whats "${@}"

It works great when I call it this way:

whats shell\ script dns #it ouputs two definitions (shell script and dns)

However I'd also to call it this way:

echo shell\ script dns | whats

I'm just used to it, all other unix commands can do it, how would you implement it in a shell script?

10
  • And how would you handle echo shell\ script dns | whats some\ other\ stuff foo? Apr 26, 2014 at 19:49
  • Last comment: whats shell\ script dns is actually shorter and easier to parse than echo shell\ script dns | whats. So why would you read stdin anyways? Apr 26, 2014 at 19:51
  • 1
    I have a strange feeling I met this question somewhere else. And I asked the very same questions as @gniourf_gniourf.
    – choroba
    Apr 26, 2014 at 19:59
  • @choroba you're right, it's still in google's cache :). Apr 26, 2014 at 20:02
  • yes, I've plenty @gniourf_gniourf, sed, grep, cut, awk, xargs, all of them can take input from stdin, I want my scripts to be able to accept stdin as well. When I get stdin and parameters I'll parse both. Apr 26, 2014 at 20:16

1 Answer 1

0

After reading the following references:

I've edited the above script as follows:

#!/bin/sh

if [ ! -t 0 ]; then
    #there is input comming from pipe or file, add to the end of $@
    set -- "${@}" $(cat)
fi

[ "${#}" -eq "0" ] && (printf "%s\\n" "${0}: word ..." >&2; exit 1)

_whats()
{
    [ -z "${1}" ] && return 1
    [ -z "${2}" ] && more_than_one="1"

    for word; do
        response="$(dig +short txt ${word}.wp.dg.cx)"
        printf "%s\\n" "${response}"
        if [ -z "${more_than_one}" ]; then
            printf "\\n%s\\n\\n" ":::::::::::::::::::::::::::::::::::::::::"
        fi
    done
}

_whats "${@}"

Which will concatenate args + stdin in $@, so now it will work in the following scenarios:

whats dns script #it outputs two definitions
echo dns script | whats #same outputs as above
echo dns script | whats ip #outputs ip, dns and script definition in that order

It will parse correctly spaces with they came as args

whats shell\ script dns #output two definitions

But not when those parameters are passed through a pipe:

echo shell\ script dns | whats #output three definitions

However that's a problem other unix utilities have too (-print0, -0, etc), so I can live with it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .