Reputation: 1
I am new to bash and I just to ask if below code (multiple if statements) can be converted into array? Here:
if [ "$(egrep -l 'PRODUCT' $LINE)" ];then
VALUE='PRODUCT'
elif [ "$(egrep -il 'SERVICE' $LINE)" ]; then
VALUE='SERVICE'
elif [ "$(egrep -il 'COMMERCE' $LINE)" ]; then
VALUE='COMMERCE'
elif [ "$(egrep -il 'EDUCATION' $LINE)" ]; then
VALUE='EDUCATION'
else
VALUE='OTHERS'
fi
Upvotes: 0
Views: 67
Reputation: 125798
If I understand what you're looking for, you can do something like this:
VALUE_OPTIONS=(PRODUCT SERVICE COMMERCE EDUCATION)
VALUE='OTHERS' # Default value, in case none of the "real" values match
for V in "${VALUE_OPTIONS[@]}"; do
if egrep -iq "$V" "$LINE"; then
VALUE="$V"
break
fi
done
This loops through all of the elements of VALUE_OPTIONS; if it finds a match, it sets VALUE to the matched element, then uses break
to skip checking the other elements. If nothing matches, VALUE remains set to 'OTHERS' after the loop.
Note that I replaced [ "$(egrep ... )" ]
with just egrep -s
-- the if
statement checks the exit status of the command, and egrep
succeeds if it finds a match, fails otherwise. Since this means we don't need (or want) it to print the actual match, I added the -q
("quiet") option to suppress output, and removed the -l
option because listing the file the match was found in is doubly irrelevant.
BTW, that egrep
command looks wrong. Are you trying to search in LINE, or in a file whose name is stored in LINE? Because egrep
expects to be given filenames, not the text to search in. If LINE has the text, you should use:
if echo "$LINE" | egrep -iq "$V"; then
In either case, you should almost certainly put $LINE
in double-quotes (as I did above), to avoid unexpected interpretation (word splitting, wildcard expansion, ...) of its contents. In shell scripts, almost all variable references should be double-quoted.
Upvotes: 1