Menu
CoddyTech

Slicing Strings

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 16 of 39.

Bash can measure and cut the text in a variable without another program. ${#s} is the length of s. ${s:start:length} takes a slice: start counts from 0, and length is how many characters to keep.

day="Wednesday"
echo "${#day}"      # 9
echo "${day:0:3}"   # Wed
echo "${day:3:3}"   # nes
echo "${day: -3}"   # day

A negative start counts from the end, and a slice without a length runs to the end. Keep the space before the minus: ${day:-3} is a different expansion and prints Wednesday.

echo "${day^^}"     # WEDNESDAY
echo "${day,,}"     # wednesday

^^ turns every letter to uppercase and ,, to lowercase. None of these change the variable itself. Store a result to work on it further: low=${day,,}, then ${low:0:3} is wed.

challenge icon

Challenge

Easy

Write a script that makes a name badge from a surname.

  1. Open badge.sh. Its first argument is a surname.
  2. Print Badge: followed by the surname in uppercase.
  3. Print Letters: followed by the length of the surname.
  4. Print Code: followed by the first three letters, a -, and the last two letters, all in lowercase.
  5. Save the file.

Try it: run bash badge.sh Johnson. It prints:

Badge: JOHNSON
Letters: 7
Code: joh-on

Then run bash badge.sh DeLuca, which mixes cases:

Badge: DELUCA
Letters: 6
Code: del-ca

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground