Bash – Get first character in string
To get first character in a string in Bash scripting, you can use the following syntax.
</>
Copy
${string:0:1}
where
:0is the index from which we would like to extract the characters instring.:1afterindexspecifies that we would like to extract only one character from thestring.
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
</>
Copy
#!/bin/bash
str="mango"
ch=${str:0:1}
echo $ch
Output
sh-3.2# ./example.sh
m
References
Conclusion
In this Bash Tutorial, we learned how to get the first character in given string.
