I understand this has been asked before but the answer don't quite give me what I need. I pgrep for a given string which returns a list of PID's containing that string in a variable ($testpid in this case). I then try and split each one of the PID's out, they are sepereated with a space like so:
PIDS:
17717 172132 2138213
Code:
IFS=" " read -a pidarray <<< "$testpid"
echo pidarray[0]
*instead of the echo above i would be assigning each item in the array to its own variable
But I get the following error:
syntax error: redirection unexpected
Your syntax was almost correct:
IFS=' ' read -r -a pidarray <<< "$testpid"
echo "${pidarray[0]}"
Note the curly braces needed for the array dereference.
More importantly, check that your shebang is #!/bin/bash
, or that you executed your script with bash yourscript
, not sh yourscript
. The error given is consistent with a shell that doesn't recognize <<<
as valid syntax -- which any remotely modern bash always will when invoked as bash; even if /bin/sh
points to the same executable, it tells bash to disable many of its extensions from the POSIX spec.
Now, that said -- if your goal is to assign each entry to its own variable, you don't need (and shouldn't use) read -a
at all!
Instead:
IFS=' ' read -r first second third rest <<<"$testpid"
printf '%s\n' "First PID is $first" "Second PID is $second"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With