For a Bash function my_fun
, how can I use a delimiter (e.g. ";") to split input into an array of strings?
Example input:
$ my_fun This is ; an example
Example output:
string1: This is
string2: an example
Perhaps using $IFS=';'
or the read
command?
No need to loop, no need to read
, simply assign an array with IFS
set to ;
:
my_fun() { IFS=';' arr=( $@ ); printf '|%s|\n' "${arr[@]}"; }
my_fun "foo ; bar ; baz"
|foo |
| bar |
| baz|
As noted in comments this may break if the input contains glob patterns (like *
): pathname expansion would apply. If this can happen you can enable/disable the noglob
option:
my_fun() { set -f; IFS=';' arr=( $@ ); set +f; printf '|%s|\n' "${arr[@]}"; }