String Basics
Strings are the most fundamental data type in Bash scripting. Unlike many other programming languages, Bash treats almost everything as a string unless specified otherwise. In this lesson, we'll cover how to define strings, the importance of quoting, and basic operations like concatenation and length calculation.
Defining Strings
In Bash, you can assign a string to a variable simply by using the equals sign
=. There should be no spaces around the equals sign.
Click Run to execute your code
name=John Doe will cause an error, but
name="John Doe" works correctly.
Quoting Mechanisms
Bash provides three main ways to quote strings, each with different behaviors regarding variable expansion and special characters.
- Double Quotes (
" "): Allow variable expansion ($var) and command substitution ($(cmd)). - Single Quotes (
' '): Treat everything literally. No expansion occurs. - Backticks (
` `): Used for command substitution (legacy). It's recommended to use$(...)instead.
Click Run to execute your code
echo 'Hello $USER' prints literally Hello $USER.
echo "Hello $USER" prints Hello anish (or your
username).
String Concatenation
Concatenating strings in Bash is straightforward: just place them next to each other.
part1="Hello"
part2="World"
combined="$part1 $part2" # Result: "Hello World"
combined2="${part1}World" # Result: "HelloWorld" (using braces to separate variable name)
String Length
You can find the length of a string stored in a variable using the
${#variable} syntax.
text="abcdef"
echo ${#text} # Output: 6
Summary
- Use
var="value"to assign strings. No spaces around=. - Use double quotes when you need variable expansion.
- Use single quotes for literal strings.
- Use
${#var}to get the length of a string.
What's Next?
Now that you understand the basics, let's look at how to modify and extract parts of strings in the next lesson on String Manipulation.
Enjoying these tutorials?