Split a variable into several variables

I understand that this was asked earlier, but the answer did not quite give me what I needed. I pgrep for a given string that returns a list of PIDs containing this string in a variable ($ testpid in this case). Then I try to split each of the PIDs, they are separated by the following space:

PIDS:

17717 172132 2138213 

code:

 IFS=" " read -a pidarray <<< "$testpid" echo pidarray[0] 

* instead of the echo above, I will assign each element in the array to my variable

But I get the following error:

 syntax error: redirection unexpected 
+6
source share
2 answers

Your syntax was almost correct:

 IFS=' ' read -r -a pidarray <<< "$testpid" echo "${pidarray[0]}" 

Note the curly braces needed to dereference an array.

More importantly, check that your shebang is #!/bin/bash , or that you executed your script with bash yourscript , not sh yourscript . The specified error is consistent with a shell that does not recognize <<< as a valid syntax that any remote modern bash will always have when calling bash; even if /bin/sh points to the same executable, it tells bash to disable many of its extensions from the POSIX specification.


Now that you have said - if your goal is to assign each record to your own variable, you do not need (and should not 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" 
+5
source

You can try this.

 testpid="17717 172132 2138213" set -- $testpid echo -e $1 $2 

After that, use $1,$2,$3 to get it separately.

+1
source

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


All Articles