100

I have as simple function in a bash script and I would like to pipe stdout to it as an input.

jc_hms(){
  printf "$1"
}

I'd like to use it in this manner.

var=`echo "teststring" | jc_hms`

Of course I used redundant functions echo and printf to simplify the question, but you get the idea. Right now I get a "not found" error, which I assume means my parameter delimiting is wrong (the "$1" part). Any suggestions?

Originally the jc_hms function was used like this:

echo `jc_hms "teststring"` > //dev/tts/0

but I'd like to store the results in a variable for further processing first, before sending it to the serial port.

EDIT: So to clarify, I am NOT trying to print stuff to the serial port, I'd like to interface to my bash functions should the "|" pipe character, and I am wondering if this is possible.

EDIT: Alright, here's the full function.

jc_hms(){
  hr=$(($1 / 3600))
  min=$(($1 / 60))
  sec=$(($1 % 60))

  printf "$hs:%02d:%02d" $min $sec
}

I'm using the function to form a string which come this line of code

songplaytime=`echo $songtime | awk '{print S1 }'`
printstring="`jc_hms $songplaytime`"  #store resulting string in printstring

Where $songtime is a string expressed as "playtime totaltime" delimited by a space.

I wish I can just do this in one line, and pipe it after the awk

printstring=`echo $songtime | awk '{print S1 }' | jc_hms`

like so.

jliu83
  • 1,553
  • 5
  • 18
  • 23
  • 3
    Your problem is that "$1" is a command-line argument to the function, not standard input, which is where the text from the pipe will be found. – chepner Jul 12 '12 at 15:02
  • 1
    So how would I access the standard input. Example? – jliu83 Jul 12 '12 at 15:51
  • 2
    I think this might be an [XY problem](http://mywiki.wooledge.org/XyProblem). Can you please update your question to tell us what you're really trying to achieve, rather than how you're trying to achieve it? – ghoti Jul 12 '12 at 15:54
  • jliu83: if `jc_hms` is on the receiving end of a pipe, stdin will be presented to the first command inside the function. But please, post what jc_hms *really* looks like, so we can determine the best solution in your case. – chepner Jul 12 '12 at 16:03
  • please notice that your function is wrong. it should really be like `jc_hms() { hr=$(($1 / 3600)); min=$((($1 % 3600) / 60)); sec=$((1 % 60)); printf "$hs:%02d:%02d" $min $sec; }` – Jo So Jul 12 '12 at 20:14

8 Answers8

92

To answer your actual question, when a shell function is on the receiving end of a pipe, standard input is inherited by all commands in the function, but only commands that actually read form their standard input consume any data. For commands that run one after the other, later commands can only see what isn't consumed by previous commands. When two commands run in parallel, which commands see which data depends on how the OS schedules the commands.

Since printf is the first and only command in your function, standard input is effectively ignored. There are several ways around that, including using the read built-in to read standard input into a variable which can be passed to printf:

jc_hms () {
    read foo
    hr=$(($foo / 3600))
    min=$(($foo / 60))
    sec=$(($foo % 60))
    printf "%d:%02d:%02d" "$hr" "$min" "$sec"
}

However, since your need for a pipeline seems to depend on your perceived need to use awk, let me suggest the following alternative:

printstring=$( jc_hms $songtime )

Since songtime consists of a space-separated pair of numbers, the shell performs word-splitting on the value of songtime, and jc_hms sees two separate parameters. This requires no change in the definition of jc_hms, and no need to pipe anything into it via standard input.

If you still have a different reason for jc_hms to read standard input, please let us know.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • I had a problem related to `read`, try this: `echo -e "\ta" |if read str;then echo "$str";fi`, it will ignore the tab and print just "a", any tip? – Aquarius Power Nov 15 '14 at 20:06
  • 1
    found fix here: http://stackoverflow.com/questions/7314044/use-bash-to-read-line-by-line-and-keep-space – Aquarius Power Nov 15 '14 at 20:13
  • `echo` is far more concluent than printf, isn't it? – Sandburg Jan 31 '19 at 15:33
  • 3
    `echo` was never fully standardized, as there were too many different (and in some cases, contradictory) implementations already in existence. (For example, the POSIX standard is for `echo` to process sequences like `\t` and `\n`, which `bash`'s implementation does *not* do unless you use the non-standard option `-e`.)' `printf` is far more portable. – chepner Jan 31 '19 at 15:37
  • 1
    "standard input is read by the first command executed inside the function" -- this isn't true. Rather, any command that reads from stdin will do so, assuming no commands before it has already consumed the stream. You could have 500 lines of "printf" and then, on the last line of the function, `cat` -- and the function would print out your 500 lines, and then `cat` would read the contents of stdin and write them to stdout. – JakeRobb Oct 30 '21 at 20:33
  • @JakeRobb Agreed, the answer is poorly worded. – chepner Oct 30 '21 at 22:57
71

You can't pipe stuff directly to a bash function like that, however you can use read to pull it in instead:

jc_hms() {
  while read -r data; do
      printf "%s" "$data"
  done
}

should be what you want

Walf
  • 8,535
  • 2
  • 44
  • 59
moopet
  • 6,014
  • 1
  • 29
  • 36
  • 1
    Can you show an example of how to use it? I would still have to use it the same way? – jliu83 Jul 12 '12 at 14:54
  • 1
    You can use this, or my answer, just as you indicated you wanted to in your question. – chepner Jul 12 '12 at 15:01
  • it'll work as you suggested. If I replace the printf with echo "manipulated $data" and run var=$(echo "teststring" | jc_hms); echo $var from the command line I get "manipulated teststring". Edited to $(..) because backticks don't show up in comments, but your original assignment should work – moopet Jul 12 '12 at 15:02
  • This does it for me. is there any way to read all the data in one shot with a one-liner? – Avindra Goolcharan Nov 18 '14 at 20:20
  • 4
    It should be `printf "%s" "$data"` or else the `$data` will be intrepeted as a format string. – Raphael Ahrens Oct 22 '15 at 07:13
67

1) I know this is a pretty old post

2) I like most of the answers here

However, I found this post because I needed to something similar. While everyone agrees stdin is what needs to be used, what the answers here are missing is the actual usage of the /dev/stdin file.

Using the read builtin forces this function to be used with piped input, so it can no longer be used in a typical way. I think utilizing /dev/stdin is a superior way of solving this problem, so I wanted to add my 2 cents for completeness.

My solution:

jc_hms() { 
  declare -i i=${1:-$(</dev/stdin)};
  declare hr=$(($i/3600)) min=$(($i/60%60)) sec=$(($i%60));
  printf "%02d:%02d:%02d\n" $hr $min $sec;
}

In action:

user@hostname:pwd$ jc_hms 7800
02:10:00
user@hostname:pwd$ echo 7800 | jc_hms 
02:10:00

I hope this may help someone.

Happy hacking!

user.friendly
  • 2,099
  • 14
  • 12
  • 3
    very helpful - I had exactly this need, to be able to process args or stdin in a function. – darrend Oct 01 '16 at 14:19
  • Very good! But seems to be a bashism (works under BASH but not with DASH) I put that in a file: #!/bin/sh jc_hms() { i="${1:-$( – gildux Feb 14 '18 at 20:32
  • 4
    absolute gold, thanks! on MacOS with bash 4.4 installed, I couldn't use `declare -i`, but just did my assignment: `i=${1:-$( – ptim Sep 06 '19 at 04:37
  • The only issue with this as it uses `${1}`, it doesn't accept multiple arguments if called directly. e.g. `jc_hms 7800 4321` will completely ignore the `4321` input, whereas `echo 7800 4321 | jc_hms` works as expected – ijoseph Nov 10 '21 at 20:33
  • @ijoseph I agree, this is made to support only a single argument. Given the original question, I'm not sure why there would be more than 1 arg, however, you just need a simple for loop wrapper to accomplish this: `for x; do jc_hms "$x"; done` – user.friendly Feb 28 '22 at 19:57
  • @gildux `${1:-default}` is indeed a bashism, but you can achieve assignment of default values in a POSIX manner without much trouble. Something like `i="$1"; [ -z "$i" ] && i="$( – Steen Schütt Aug 25 '22 at 07:36
  • @SteenSchütt no… `${1:-default}` is POSIX (hence not a bashism). See https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02 The bash stuff there, in fact, was `$( – gildux Aug 26 '22 at 10:18
29

Or, you can also do it in a simple way.

jc_hms() {
    cat
}

Though all answers so far have disregarded the fact that this was not what OP wanted (he stated the function is simplified)

Jo So
  • 25,005
  • 6
  • 42
  • 59
  • Thanks for this; now I know I can use this for piping into `printf`, e.g. ``xdotool search --onlyvisible --name 'Audacity' | printf "0x%08x\n" `cat` `` – sdaau Oct 18 '13 at 04:44
  • 1
    You actually can using this method, refer to my answer below: `# echo 12345-1234 | printf 'Zip: %s\n' $( – user.friendly Feb 19 '16 at 18:40
  • @TrueFalse: Yes, that works, but it uses the shell to convert back from stdin to arguments for `printf`. `printf` never reads from stdin, there is no point piping to it. (What you do is the same as `printf 'Number: %d\n' $(echo 1 2 3 4)`) – Jo So Feb 19 '16 at 20:31
  • @Jo So: That's true and the same can be said about the OP's question. Using it in the way that I used here is pointless but its demonstrating the method. You said you cannot pipe into printf; that's not really true, so I was simply making an argument for anyone who may very well wish to pipe to printf. – user.friendly Feb 19 '16 at 22:08
  • @TrueFalse: You *can not* pipe into printf. You pipe into `<`, which is short for `cat`, and let the shell perform command substitution (which puts the output of the `cat` as arguments to `printf`). – Jo So Feb 19 '16 at 22:28
  • 1
    Well done. This works for a wide range of things if you want to pipe to a subsequent command. Good to know. – JJ Ward Apr 15 '22 at 07:23
  • I was looking for a way to use a pipe as the input to a bash function and your suggestion of using `cat` solved my problem. Thanks! – Noah Sussman Aug 29 '22 at 16:10
22

I like user.friendly's answer using the Bash built-in conditional unset substitution syntax. Here's a slight tweak to make his answer more generic, such as for cases with an indeterminate parameter count:

function myfunc() {
    declare MY_INPUT=${*:-$(</dev/stdin)}
    for PARAM in $MY_INPUT; do
        # do what needs to be done on each input value
    done
}
datatype_void
  • 433
  • 5
  • 23
Der Schley
  • 466
  • 4
  • 6
  • Could you explain how `${*:-$( – user56834 Nov 21 '21 at 15:33
  • 1
    @user56834 $1 or ${1} is the first positional parameter. $* or ${*} (also $@) are all positional parameters. In Bash parameter substitution, `:-` sets a default value in case the parameter you are accessing has no value. `$( )` is command substitution and executes whatever is inside. `<` is shorthand for `cat`, which reads file content. In this case, the file is /dev/stdin. – user.friendly Feb 28 '22 at 20:09
1

Hmmmm....

songplaytime=`echo $songtime | awk '{print S1 }'`
printstring="`jc_hms $songplaytime`"  #store resulting string in printstring

if you're calling awk anyway, why not use it?

printstring=`TZ=UTC gawk -vT=$songplaytime 'BEGIN{print strftime("%T",T)}'`

I'm assuming you're using Gnu's Awk, which is the best one and also free; this will work in common linux distros which aren't necessarily using the most recent gawk. The most recent versions of gawk will let you specify UTC as a third parameter to the strftime() function.

Medievalist
  • 713
  • 5
  • 8
1

The proposed solutions require content on stdin or read to be only conditionally called. Otherwise the function will wait for content from the console and require an Enter or Ctrl+D before continuing.

A workaround is to use read with a timeout. e.g. read -t <seconds>

function test ()
{
  # ...
  # process any parameters
  # ...
  read -t 0.001 piped
  if [[ "${piped:-}" ]]; then
    echo $piped
  fi
}

Note, -t 0 did not work for me.
You might have to use a different value for the time-out. Too small a value might result in bugs and a too large time-out delays the script.

Farway
  • 741
  • 10
  • 13
  • A better test for empty stdin seems to be `[[ ! -t 0 ]]` as in this answer: https://unix.stackexchange.com/a/388462/84777 – mattmc3 Jan 05 '22 at 16:00
1

seems nothing works, but there are work arounds

mentioned work around xargs ref function

$ FUNCS=$(functions hi); seq 3 | xargs -I{} zsh -c "eval $FUNCS; hi {}"

then this doesn't work either because your function could reference another function. so I ended up writing some function that accepts pipe inputs, like this:

somefunc() {
    while read -r data; do
        printf "%s" "$data"
    done
}
zinking
  • 5,561
  • 5
  • 49
  • 81