Maybe you can just do something like:
string=element1,element2,element3 element=element2 case ",$string," in (*,"$element",*) echo element is in string;; (*) echo it is not;; esac
(standard sh
syntax).
To work with arrays or split strings, bash is one the poorest choices of shells.
With zsh
, to split a string on a given separator, there's a dedicate operator: the s
plit parameter expansion flag:
array=( "${(@s[,])string}" )
(@
and quotes used to preserve empty elements like with the "$@"
of the Bourne shell)
To check whether an array has a given element:
if (( $array[(Ie)$element] )); then print element is in the array else print it is not fi
To split in bash
, you can use the split+glob operator (which you did a bit awkwardly with the unquoted $(...)
) like in ksh/sh:
IFS=, # split on , instead of the default of SPC/TAB/NL set -o noglob # disable the glob part which you don't want array=( $string'' ) # split+glob; '' added to preserve an empty trailing element # though that means an empty $string is split into one empty # element rather than no element at all
To lookup array, bash has not dedicated operator either, but you could define a helper function:
is_in() { local _i _needle="$1" local -n _haystack="$2" for _i in "${_haystack[@]}"; do [ "$_i" = "$_needle" ] && return done false } if is_in "$element" array; then echo element is in the array else it is not fi
a,b,"c d","e,f ""g"",h"
which encodes the valuesa
,b
,c d
, ande,f "g",h
(quoted fields may also contain newlines).