0

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!

  • 1
    How exactly are you running this? are you sure it's being interpreted by bash (not sh for example)? – steeldriver Mar 30 at 13:39
  • I have #!/bin/bash at the top of the .sh file, if that answers your question. Then I run sh filename.sh to run it. – etsnyman Mar 30 at 14:06
3

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

| improve this answer | |
  • Thank you! This has appeared to fix the problem. It also seems to work if I run bash filename.sh – etsnyman Mar 30 at 14:29
  • 2
    @etsnyman yes bash filename.sh will work - but try to get out of the habit of second-guessing the correct interpreter (that's what the shebang is for) – steeldriver Mar 30 at 14:32
  • Will do. Thanks. – etsnyman Mar 30 at 14:32
0

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

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.