Command Substitution in Shell

Level 4159 keystrokes

Command substitution $(command) runs a command and inserts its output, here to store today's date and a file count in variables and build a backup file name. The numbers and date in the output vary.

Shell code

# $(...) captures date's output, e.g. 2024-01-15
1current_date=$(date +%Y-%m-%d)
# ${current_date} inserts the value into the name; braces separate it from the text after it
2backup_file="backup_${current_date}.tar.gz"
# Capture a pipeline's output: the number of files under the current directory
3file_count=$(find . -type f | wc -l)
# Print both values; they vary with the files and the date
4echo "Files: $file_count, Backup: $backup_file"

Output

Files: 42, Backup: backup_2024-01-15.tar.gz
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • _× 7
  • $× 5
  • -× 4
  • "× 4
  • .× 3
  • %× 3
  • =× 3
  • :× 2
  • (× 2
  • )× 2

More Shell examples at level 4

← Shell typing practice