Skip to main content

How to Get First Character of String

• 2 min read
bash

Quick Answer: Get the First Character of a String

To extract the first character of a string in Bash, use parameter expansion with substring syntax: ${string:0:1}. This is the fastest pure-Bash method. Alternatively, use cut -c1 or sed for piped input.

Quick Comparison: First Character Extraction Methods

MethodSpeedBest ForCompatibility
Parameter expansionFastestVariables, simple extractionAll Bash
cut -c1Very fastPiped input, streamsAll systems
sed ‘s/.//g’FastComplex patternsAll systems
head -c1Very fastStreamsAll systems
Substring with #Very fastAdvanced patternsBash 3.x+

Bottom line: Use parameter expansion for variables, use cut for piped input.


Extracting the First Character

Getting the first character of a string is useful for validating input, extracting initials, processing filenames, or text categorization. Bash provides several efficient methods.

Using Parameter Expansion

The cleanest method uses Bash’s parameter expansion:

#!/bin/bash

string="Hello"

# Get first character
first="${string:0:1}"
echo "First character: $first"
# Output: H

# Extract first 3 characters
first_three="${string:0:3}"
echo "First three: $first_three"
# Output: Hel

The syntax ${string:offset:length} means:

  • 0 = start at position 0 (first character)
  • 1 = get 1 character

Using cut Command

The cut command can also extract the first character:

#!/bin/bash

string="Hello"

# Get first character using cut
first=$(echo "$string" | cut -c1)
echo "First character: $first"
# Output: H

# Get first N characters
first_three=$(echo "$string" | cut -c1-3)
echo "First three: $first_three"
# Output: Hel

Comparing Methods

Parameter expansion is faster (no subprocess), but here’s what each does:

#!/bin/bash

text="Bash"

# Method 1: Parameter Expansion (fastest)
first="${text:0:1}"

# Method 2: cut command
first=$(echo "$text" | cut -c1)

# Method 3: head with od
first=$(echo -n "$text" | head -c1)

# All produce: B
echo "$first"

Practical Example: File Extension Handler

#!/bin/bash

filename="document.txt"

# Get first character to validate
first_char="${filename:0:1}"

if [ "$first_char" = "." ]; then
  echo "Hidden file (starts with dot)"
else
  echo "Regular file"
fi

Validating Input

Check if a string starts with a specific character:

#!/bin/bash

validate_input() {
  local input="$1"

  # Get first character
  first="${input:0:1}"

  case "$first" in
    "#")
      echo "Comment line"
      return 0
      ;;
    "@")
      echo "Tag"
      return 0
      ;;
    "-")
      echo "Option flag"
      return 0
      ;;
    *)
      echo "Unknown format"
      return 1
      ;;
  esac
}

validate_input "#This is a comment"
validate_input "@mention"
validate_input "-verbose"

Real-World Example: Name Initialization

Extract initials from names:

#!/bin/bash

extract_initials() {
  local fullname="$1"
  local first_word="${fullname%% *}"  # Get first word
  local first_char="${first_word:0:1}"

  echo "$first_char"
}

# Usage
name="John Doe"
initial=$(extract_initials "$name")
echo "Initial: $initial"
# Output: J

Handling Edge Cases

What if the string is empty?

#!/bin/bash

get_first_safe() {
  local string="$1"

  # Check if string is empty
  if [ -z "$string" ]; then
    echo "ERROR: String is empty"
    return 1
  fi

  # Get first character
  echo "${string:0:1}"
  return 0
}

# Test cases
get_first_safe "Hello"     # Output: H
get_first_safe ""          # Output: ERROR: String is empty
get_first_safe "A"         # Output: A

Extracting Multiple Characters from Start

Get the first N characters:

#!/bin/bash

string="Programming"

# First 1 character
echo "${string:0:1}"     # P

# First 3 characters
echo "${string:0:3}"     # Pro

# First 5 characters
echo "${string:0:5}"     # Progr

# All but first (using negative indexing)
echo "${string:1}"       # rogramming

Practical Example: Process Lines

#!/bin/bash

process_file() {
  local filename="$1"

  while IFS= read -r line || [[ -n "$line" ]]; do
    # Skip empty lines
    [ -z "$line" ] && continue

    # Get first character
    first_char="${line:0:1}"

    # Skip comments
    if [ "$first_char" = "#" ]; then
      continue
    fi

    # Process the line
    echo "Processing: $line"
  done < "$filename"
}

process_file "config.txt"

Performance: Parameter Expansion is Fastest

#!/bin/bash

# Time different methods
string="The Quick Brown Fox"

# Method 1: Parameter expansion (fastest - no subshell)
time for ((i=0; i<10000; i++)); do
  first="${string:0:1}"
done

# Method 2: cut command (slow - spawns subshell)
time for ((i=0; i<10000; i++)); do
  first=$(echo "$string" | cut -c1)
done

Parameter expansion is significantly faster because it doesn’t spawn a subshell.

Uppercase First Character

A common pattern - capitalize first letter:

#!/bin/bash

capitalize_first() {
  local string="$1"
  local first="${string:0:1}"
  local rest="${string:1}"

  # Convert first to uppercase
  first=$(echo "$first" | tr '[:lower:]' '[:upper:]')

  echo "${first}${rest}"
}

# Usage
capitalize_first "hello"    # Output: Hello
capitalize_first "bash"     # Output: Bash

Important Notes

  • Parameter expansion ${var:offset:length} is the fastest method
  • The cut -c1 method works but requires a subshell (slower)
  • Empty strings return empty (no error)
  • Position 0 is the first character (zero-indexed)
  • Use quotes to handle strings with spaces

Quick Reference

# Get first character
first="${string:0:1}"

# Get first N characters
first_n="${string:0:5}"

# Using cut
first=$(echo "$string" | cut -c1)

# Get all except first character
rest="${string:1}"

# Check if starts with character
[[ "$string" = "X"* ]] && echo "Starts with X"

Summary

Extracting the first character from a string is easy in Bash using parameter expansion. The syntax ${string:0:1} is fast, efficient, and doesn’t require external commands. Use this technique for validation, parsing, and text processing.