1

I'm trying to write a bash script that will manipulate the data piped from xsel.

...
ary=()
while read data; do
    echo $data
    ary=( "${ary[@]}" "$data" )
done

The problem is there is nothing being read when I call:

xsel | myscript.sh

I have tried

echo "testing testing" | myscript.sh

and that works, and I also made sure there was something coming from xsel

xsel | festival --tts --pipe
# will read the clipboard string piped from xsel aloud

Any Suggestions? Thanks in advance

RBI
  • 803
  • 2
  • 14
  • 25
  • possible duplicate of [Bash script, read values from stdin pipe](http://stackoverflow.com/questions/2746553/bash-script-read-values-from-stdin-pipe) – dkinzer May 30 '14 at 23:32

1 Answers1

6

read fails if it can't read a full line, and xsel doesn't output a line feed.

Replace your loop with:

readarray ary   # new in Bash 4

If you're only adding lines in an array as a proxy for sticking all the data in a variable, you can instead do:

input=$(cat)
that other guy
  • 116,971
  • 11
  • 170
  • 194
  • You forgot to add `-t` to `readarray`. Also, using timeout (`-t`) for `read` could also be helpful. – konsolebox May 31 '14 at 07:30
  • `-t` strips trailing newlines, but the original problem seems to be that there is no trailing newline to strip. – chepner May 31 '14 at 13:59
  • @chepner If the OP actually expects data to be not multi-lined, then using a single `read` would be enough. `readarray` would not be needed. – konsolebox May 31 '14 at 14:26
  • By the way I'm not sure if your edit applies as it's not reading input from a file but from a command. – konsolebox May 31 '14 at 14:28