What if START is negative?

QuestionsQuestions8 SkillsProBasic String OperationsNov, 08 2025
093

In Bash, if the START index is negative in the substring extraction syntax ${STRING:$START:$LENGTH}, it counts from the end of the string rather than the beginning.

For example, if you have the following:

STRING="The quick brown fox"
START=-3
LENGTH=3

Using the syntax ${STRING:$START:$LENGTH} would extract 3 characters starting from the third character from the end of the string. In this case, it would result in the substring "fox".

Here's how it works:

  • The string "The quick brown fox" has a length of 19 characters.
  • A START value of -3 means to start from the 3rd character from the end, which is the character f.
  • The LENGTH of 3 means to extract 3 characters starting from f.

So, the command would look like this:

SUBSTRING=${STRING:$START:$LENGTH}

This would assign the value "fox" to the variable SUBSTRING.

0 Comments

no data
Be the first to share your comment!