</>
Skip to content
Bash lessons (7/29)

Bash — Strings

String basics

#!/bin/bash

s="Hello, World!"

echo "Length: ${#s}"           # 13
echo "Substring: ${s:0:5}"    # Hello
echo "Replace: ${s/World/Bash}" # Hello, Bash!
echo "Uppercase: ${s^^}"      # HELLO, WORLD!
echo "Lowercase: ${s,,}"      # hello, world!

String comparison

#!/bin/bash

a="hello"
b="hello"
c="world"

[ "$a" = "$b" ] && echo "Equal"
[ "$a" != "$c" ] && echo "Not equal"
[ -z "$empty" ] && echo "Empty string"
[ -n "$a" ] && echo "Non-empty string"

String concatenation

#!/bin/bash

first="Hello"
second="World"
combined="$first $second"
echo "$combined" # Hello World

String length

#!/bin/bash

s="Hello"
echo "${#s}" # 5

Substring

#!/bin/bash

s="Hello, World!"
echo "${s:0:5}"   # Hello
echo "${s:7}"     # World!
echo "${s: -6}"   # World!

String replacement

#!/bin/bash

s="Hello, World!"
echo "${s/World/Bash}"    # Hello, Bash!
echo "${s//l/L}"          # HeLLo, WorLd!
echo "${s/#Hello/Hi}"    # Hi, World!
echo "${s/!//}"           # Hello, World

Quoting

#!/bin/bash

name="Alice"

# Double quotes: variable expansion
echo "Hello, $name"     # Hello, Alice

# Single quotes: literal
echo 'Hello, $name'     # Hello, $name

# Backslash: escape
echo "Price: \$100"     # Price: $100

Mini Practice

Write Bash code that:

  1. Extracts a substring from a string
  2. Replaces text in a string
  3. Demonstrates quoting differences
  4. Checks string length and emptiness

Up Next

In the next lesson, you'll learn about Numbers — arithmetic operations in Bash.

Related Topics

Frequently Asked Questions about Strings

What is Strings in Bash?

Strings is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Strings?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Strings.

Why is Strings important in Bash?

Strings is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.