Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the POSIX shell equivalent of bash <<<

Tags:

bash

sh

I have a variable that looks sort of like this:

msg="newton apple tree"

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

read a b c <<< $msg

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

like image 862
Bitdiot Avatar asked Nov 10 '14 17:11

Bitdiot


People also ask

What is POSIX in bash?

POSIX Shell is a command line shell for computer operating system which was introduced by IEEE Computer Society. POSIX stands for Portable Operating System Interface. POSIX Shell is based on the standard defined in Portable Operating System Interface (POSIX) – IEEE P1003.

Is bash a Posix shell?

bash is not a POSIX compliant shell. It is a dialect of the POSIX shell language. Bash can run in a text window and allows the user to interpret commands to do various tasks. It has the best and most useful features of the Korn and C shells, such as directory manipulation, job control, aliases, and many others.

Is bash POSIX compatible?

Bash can be configured to be POSIX-conformant by default, by specifying the --enable-strict-posix-default to configure when building (see Optional Features).

What is a POSIX compatible shell?

POSIX defines the application programming interface (API), along with Unix command line shells and utility interfaces. This ensure software compatibility with flavors of Unix and other operating systems. The POSIX shell is implemented for many UNIX like operating systems.


2 Answers

A here string is just syntactic sugar for a single-line here document:

$ msg="foo * bar"
$ read a b c <<EOF
> $msg
> EOF
$ echo "$a"
foo
$ echo "$b"
*
$ echo "$c"
bar
like image 105
chepner Avatar answered Oct 28 '22 21:10

chepner


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

The POSIX way of splitting a string known to have three words into three arguments, similar but not identical to read is:

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"
like image 40
that other guy Avatar answered Oct 28 '22 19:10

that other guy