Как сделать канал сценария оболочки осведомленным
У меня есть следующий скрипт:
#!/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 "${@}"
Это прекрасно работает, когда я называю это так:
whats shell\ script dns #it ouputs two definitions (shell script and dns)
Однако я бы также назвал это так:
echo shell\ script dns | whats
Я просто привык к этому, все другие команды Unix могут это сделать, как бы вы реализовали это в сценарии оболочки?
1 ответ
Решение
После прочтения следующих ссылок:
- https://unix.stackexchange.com/questions/61183/bash-script-that-reads-filenames-from-a-pipe-or-from-command-line-args
- http://www.linuxjournal.com/content/working-stdin-and-stdout
- http://mockingeye.com/blog/2013/01/22/reading-everything-stdin-in-a-bash-script/
Я отредактировал приведенный выше скрипт следующим образом:
#!/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 "${@}"
Который объединит args + stdin в $@, поэтому теперь он будет работать в следующих сценариях:
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
Это будет правильно анализировать пробелы, как они пришли в качестве аргументов
whats shell\ script dns #output two definitions
Но не тогда, когда эти параметры передаются через канал:
echo shell\ script dns | whats #output three definitions
Однако это проблема, с которой сталкиваются и другие утилиты Unix (-print0, -0 и т. Д.), Так что я могу с этим смириться.