Bash – Get character at specific index in string

To get character at specific index in a string in Bash scripting, you can use the following syntax.

${string:index:1}

where

  • index is the specific position from which we would like to extract the character in string.
  • :1 after index specifies that we would like to extract only one character from the string.

Example

In the following script, we take a string in str. We get the character at index=5 using the expression given above.

example.sh

#!/bin/bash
 
str="abcdefghihklm"
index=5
ch=${str:index:1}
echo $ch

Output

sh-3.2# ./example.sh 
f

References

Bash Substring

ADVERTISEMENT

Conclusion

In this Bash Tutorial, we learned how to get the character at specific index from given string.