2

This seems like it should be stupid easy but I can't seem to get it to work! I have a string I want to divide into an array based on new lines.

This below is basically what I'm trying to do.

echo $devices
serial1 device
serial2 device

arr=$(magic_function $devices)
echo ${arr[0]}
serial1 device
echo ${arr[1]}
serial2 device

1 Answer 1

3

The IFS (internal field separator) determines how words are split in bash. Unquoted expansions are always split. By default, this is \t, \n, and ' '. You can set it to just \n to have your words split on a newline only.

IFS=$'\n' arr=( $(yourfunc "$devices") )

Another option on newer versions of bash (4.0+), is the mapfile command.

mapfile -t arr < <(yourfunc "$devices")
Sign up to request clarification or add additional context in comments.

2 Comments

should be an easier way for sure, but it works. Also I called unset IFS when I was done so it wouldn't change for other programs.
Note that IFS is usually set by default, so unsetting it is different than restoring it to its old value.

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.