Convert String in Shell Script

String manipulation is an essential part of Shell scripting. In this tutorial, we will explore various operations you can perform on strings, such as converting cases and finding the length of a string.


Convert First Character to Upper Case in Shell Script

You can convert the first character of a string to uppercase using the following syntax:

#!/bin/bash
string="my name is Gaurav"
echo "${string^}" # My name is Gaurav

Convert a String to Upper Case in Shell Script

To convert the entire string to uppercase:

#!/bin/bash
string="my name is Gaurav"
echo "${string^^}" # MY NAME IS GAURAV

Convert First Character to Lower Case in Shell Script

To convert the first character of a string to lowercase:

#!/bin/bash
string="My name is Gaurav"
echo "${string,}" # my name is Gaurav

Convert a String to Lower Case in Shell Script

To convert the entire string to lowercase:

#!/bin/bash
string="My name is Gaurav"
echo "${string,,}" # my name is gaurav

Get the Length of a String in Shell Script

To calculate the length of a string variable:

#!/bin/bash
string="My name is Gaurav"
echo "Length of the string is ${#string}"

Complete Example

Here is a complete example demonstrating all the above string manipulations:

#!/bin/bash
string="my name is Gaurav"
echo "Original string: ${string}" 
echo "First character to uppercase: ${string^}"  
echo "Entire string to uppercase: ${string^^}"  

string="My name is Gaurav"
echo "Original string: ${string}"
echo "First character to lowercase: ${string,}" 
echo "Entire string to lowercase: ${string,,}" 

echo "Length of the string: ${#string}"

Output:

┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./string-variable.sh
Original string: my name is Gaurav
First character to uppercase: My name is Gaurav
Entire string to uppercase: MY NAME IS GAURAV
Original string: My name is Gaurav
First character to lowercase: my name is Gaurav
Entire string to lowercase: my name is gaurav
Length of the string: 17

Demo Video

Click Here for Demo Video


String manipulation in Shell scripting is simple yet powerful. By mastering these techniques, you can handle strings efficiently in your scripts. Stay tuned for more tutorials!