I am attempting to check for proper formatting at the start of a string in a bash script.
The expected format is like the below where the string must always begin with "ABCDEFG-" (exact letters and order) and the numbers would vary but be at least 3 digits. Everything after the 3rd digit is a do not care. Expected start of string: "ABCDEFG-1234"
I am using the below code snippet.
[ $(echo "$str" | grep -E "ABCDEFG-[0-9][0-9][0-9]") ] && echo "yes"
str1 = "ABCDEFG-1234"
str2 = "ABCDEFG-1234 - Some more text"
When I use str1 in place of str everything works ok and yes is printed.
When I use str2 in place of str i get the below error
[: ABCDEFG-1234: unary operator expected
I am pretty new to working with bash scripts so any help would be appreciated.
-n:[ -n "$(echo "$str" | grep -E "ABCDEFG-[0-9][0-9][0-9]")" ] && echo "yes"-- that way the output fromgrepisn't string-split and passed to[ ]as separate arguments, which was the immediate cause of your error. That said, that approach is unnecessarily inefficient and baroque, whengrepcan directly emit a true or false exit status based on whether it matched, with no need for[ ]or output parsing at all, and when the shell can do comparisons without needing any external tool like grep.-nis only necessary in some pathological cases; in the common case, the quotes would be enough).