Bash – Get first character in string

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

${string:0:1}

where

  • :0 is the index from which we would like to extract the characters 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 first character in this string and echo it to output.

example.sh

#!/bin/bash
 
str="mango"
ch=${str:0:1}
echo $ch

Output

sh-3.2# ./example.sh 
m

References

Bash Substring

ADVERTISEMENT

Conclusion

In this Bash Tutorial, we learned how to get the first character in given string.