0

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.

8
  • @sorontar I want the scripts to read from stdin. So they are called like ./refimpl.sh < args.in. That part has been fixed. Commented Dec 26, 2016 at 0:11
  • @StevenPenny Adding shebang here makes the question even longer. I think either way doesn't affect the result. Commented Dec 26, 2016 at 0:14
  • 1
    If input comes on the form like "a b" c on stdin, you can do eval "arr=( $(cat) )". Commented Dec 26, 2016 at 0:15
  • @thatotherguy Why don't you write an answer then? I tested with several inputs and it looks good. The only concern I have is about the potential risk of eval which is very difficult to harness. Commented Dec 26, 2016 at 1:30
  • There's is no risk or problem with using eval that refimpl.sh doesn't already have. Commented Dec 26, 2016 at 2:14

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm not near a computer, but it looks like it will work just like refimpl.sh, which is what OP is asking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.