What is the equivalent of a POSIX bash shell <<<

I have a variable that looks something like this:

 msg="newton apple tree" 

I want to assign each of these words to separate variables. This is easy to do in bash:

 read abc <<< $msg 

Is there a compact, readable way to do this in a POSIX shell?

+5
source share
3 answers

To write idiomatic scripts, you cannot just look at each individual syntax element and try to find the POSIX equivalent. It is like translating a text by replacing each individual word with its entry in the dictionary.

A POSIX method for breaking a line that is known to have three words in three arguments, similar but not identical to read :

 var="newton apple tree" set -f set -- $var set +f a=$1 b=$2 c=$3 echo "$a was hit by an $b under a $c" 
+8
source

Here a line is just the syntactic sugar for a single line document:

 $ msg="foo * bar" $ read abc <<EOF > $msg > EOF $ echo "$a" foo $ echo "$b" * $ echo "$c" bar 
+10
source

This is not very, but as a universal solution, you can get around this with a named pipe.

From BashFAQ # 24 :

 mkfifo mypipe printf '%s\n' "$msg" >mypipe & read -rabc <mypipe 

printf more reliable / better than echo ; echo behavior changes between implementations if you have a message containing only, say, -E or -n .


However, for what you are doing here, you can simply use the parameter extension:

 a=${msg%% *}; msg=${msg#* } b=${msg%% *}; msg=${msg#* } c=${msg%% *}; msg=${msg#* } 
+3
source

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


All Articles