Bash: Read args from stdin into array

1.5k views Asked by At

Problem Description

Given a plaintext file args.in containing one line of command line arguments, read them into an array.

Problem Formulation

We have 4 files:


args.in:

"ab" c

refimpl.sh:

read -r line
bash -c "bash showargs.sh $line"

arrayimpl.sh:

arr=()

# BEGIN-------------------------
# Input comes from stdin.
# You need to set arr here.
# END---------------------------

echo "${#arr[@]}"
for i in "${arr[@]}"; do
    echo "$i"
done

showargs.sh:

echo "$#"
for i in "$@"; do
    echo "$i"
done

Put them into the same folder. We want you to implement arrayimpl.sh so that

bash refimpl.sh < args.in

and

bash arrayimpl.sh < args.in

give the same output.

Your solution should only contain a single file arrayimpl.sh.

Output Example

2
ab
c

This problem is a better formulation of this but not a dup of this. Some solutions work there but not here. For example, when we have the following input:

args.in:

"a\"b" c

There is no known solution yet.

1

There are 1 answers

1
that other guy On

The expected solution for this assignment is something equivalent to:

eval "arr=( $(cat) )"

This evaluates input as shell words, which is what refimpl.sh also does.

This is for toy problems and homework assignments only. Real software should not use executable code as a data format.