Bash: Convert string into array?

I have been Googling to no avail, so I would appreciate someone's kind help a lot.

I have a string of filenames that will be generated, and each filename is separated by the character |.

For instance, the string of filenames looks similar to:

/home/user/something or other.txt|/home/user/Downloads/something else.txt|/home/somewhere/there are spaces definitely.txt|/home/user/there are always spaces.txt|/home/user/Documents/spaces are always present.txt

I would like to split this string into an array, using the character | to split up the filenames and their locations.

I have tried this:

IFS='|' read -ra array <<< "$string"

but it does NOT work and gives me the following error message:

Syntax error: redirection unexpected

Perhaps someone much more clever than me has the solution? I would greatly appreciate it!

2

2 Answers

Your code is correct - for bash

I have #!/bin/bash at the top of the .sh file

Good

Then I run sh filename.sh to run it.

Here's the problem - you're explicitly telling the system to ignore the shebang, and run the script with sh. That likely resolves to /bin/sh which on Ubuntu is the POSIX dash shell by default.

Instead, just make your script executable

chmod +x filename.sh

and then run it using

./filename.sh

which will ensure the correct interpreter is used. See also

3

Reading string into an index array with a user defined delimiter using mapfile:

$ string='1|2|3|4'; \ mapfile -td \| <<< $string; echo ${MAPFILE[@]}

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like