What is the definition of a string in Bash?

Bash use the term "string" several places in its documentation, e.g. to document the =~ operator used for regular expression matching:

An additional binary operator, =~, is available, with the same precedence as == and !=. When it is used, the string to the right of the operator is considered a POSIX extended regular expression and matched accordingly (as in regex(3)).

In the section DEFINITIONS, I don't see any definition of strings:

       The following definitions are used throughout the rest of this document.
       blank  A space or tab.
       word   A sequence of characters considered as a single unit by the shell.  Also known as a token.
       name   A word consisting only of alphanumeric characters and underscores, and beginning with an alphabetic character or an underscore.  Also referred to as an identifier.
              A character that, when unquoted, separates words.  One of the following:
              |  & ; ( ) < > space tab newline
       control operator
              A token that performs a control function.  It is one of the following symbols:
              || & && ; ;; ;& ;;& ( ) | |& <newline>

So, what exactly are strings in Bash? May they contain whitespace or characters in the IFS environment variable?

NB: I know strings are normally defined as a series of symbols in an alphabet.

| improve this question | | | | |

The Bash manual doesn’t define strings, but it does say that

It is intended to be a conformant implementation of the IEEE POSIX Shell and Tools portion of the IEEE POSIX specification (IEEE Standard 1003.1).

so one can assume that the POSIX definition of strings applies:

A contiguous sequence of bytes terminated by and including the first null byte.

| improve this answer | | | | |
  • Thanks you. So, strings like those provided for =~ may by definition contain any character except zero-byte. But I can’t quote the entire string to preserve spaces, otherwise Bash do word splitting, since quoting the string means to interprete it as a fixed string (not a regex). Can I get around it by writing something like: a(“ “|b)c” “d+? Will Bash do word splitting here or read it as a one contiguous string, with the ” “ being interpreted as fixed spaces? Why? – Shuzheng Jan 31 at 5:41
  • You can escape spaces with backslashes: a(\ |b)c\ d+. Quoting spaces works too, Bash won’t split words; I don’t have a reference off-hand. – Stephen Kitt Jan 31 at 5:47
  • But wouldn’t my example work too? Sorry, I can’t test it right now, since I’m in transport, but will do so later. – Shuzheng Jan 31 at 5:49
  • Yes, like I said, quoting spaces works too, so your example works. – Stephen Kitt Jan 31 at 5:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.