Return an error if the input does not have exactly 1 line, otherwise the input signal to the next step

I have a series of commands connected together with pipes:

should_create_one_line | expects_one_line

The first command should_create_one_lineshould output output that has only one line, but under strange circumstances, the output may be multi-line or empty.

I would like to add a step between the two validate_one_line,:

should_create_one_line | validate_one_line | expects_one_line

If its input contains exactly 1 line, then it validate_one_linewill simply output its input. If its input contains more than 1 line or is empty, it validate_one_lineshould lead to a stop of the entire sequence of steps and the return of an error code.

Which command can I use for validate_one_line?

+4
source share
3

read. , :

exactly_one_line() {
    local line # Use to echo the line
    read -r line || return # Guarantee at least one line is read
    read && return 1 # Indicate failure if another line is successfully read
    echo "$line"
}

  • " " , . , , .
  • , a|b, a b. , b , a .

:

$ wc -l empty oneline twolines 
       0 empty
       1 oneline
       2 twolines
       3 total
$ exactly_one_line < empty; echo $?
1
$ exactly_one_line < oneline; echo $?
oneline
0
$ exactly_one_line < twolines; echo $?
1
+3

, expects_one_line. , , , validate_one_line , expects_one_line, ( ). bash , :

should_create_one_line.sh | ( var="$(cat)"; [ $(echo "$var" | wc -l) -ne 1 ] && exit 1 || echo "$var") | expects_one_line.sh

, exit 1 expects_one_line.sh - . , . , expects_one_line.sh:

input="$(cat)"
[ $(echo "$var" | wc -l) -ne 1 ] && exit 1

, expects_one_line.sh , , script.

: mutliline stdin (sh, bash)?

+1

bash script, , 1

cat, fet 1

sh -c 'while read CMD; do [ ! -z "$LINE" ] && exit 1; LINE=$CMD; done; [ -z "$LINE" ] && exit 1; printf "%s\n" $LINE | "$0" "$@"' cat

  • , 5
  • $LINE , 6
  • $LINE
  • 1
  • $LINE , 7
  • 1
  • Call our program and pass us this $ -string using printf

Usage example:

Print only if grep found 1 match:

 grep .... | sh -c 'while read CMD; do [ ! -z "$LINE" ] && exit 1; LINE=$CMD; done; [ -z "$LINE" ] && exit 1; printf "%s\n" $LINE | "$0" "$@"' cat

An example of a poster for questions:

 should_create_one_line | sh -c 'while read CMD; do [ ! -z "$LINE" ] && exit 1; LINE=$CMD; done; [ -z "$LINE" ] && exit 1; printf "%s\n" $LINE | "$0" "$@"' expects_one_line
0
source

Source: https://habr.com/ru/post/1623094/


All Articles