If you want to split a string based on a hyphen as a separator you can do this:
IFS=- read first second <<< "$r"
$ printf '%q\n' "$first"
part1\ # Note the space here
$ printf '%q\n' "$second"
\ part2
If you want to get only the words in a string you can do this:
$ read first separator second <<< "$r"
$ printf '%q\n' "$first"
part1
$ printf '%q\n' "$separator"
-
$ printf '%q\n' "$second"
part2
That said, spaces (and other special characters such as high Unicode, newlines, punctuation etc.) in file paths is a particularly thorny subject for shell programming, but they are perfectly valid. The first rule of handling special paths is quoting properly. Once you get that right, you're 90% of the way towards supporting basically any valid *nix path. The other 10% involve various tricks like using --
as a separator between arguments and paths if you need to parse arguments, starting relative paths with ./
outside scripts and "$(cd "$(dirname "${BASH_SOURCE\[0\]}")" && pwd)"
inside scripts, looping over paths using while
, and escaping special characters using $''
quotes (see man bash
). I would definitely recommend learning these and writing test cases for your script with incrementally more complex file names to guarantee that it works.