Skip to content

Latest commit

 

History

History
62 lines (37 loc) · 1.96 KB

3.md

File metadata and controls

62 lines (37 loc) · 1.96 KB

Chapter 2: The Variable Verse 🌌

3 - Concatenate variables

Concatenating Variables in Linux Shell Scripting

Concatenating variables in Linux shell scripting involves combining or joining multiple variables or strings together to create a single string. This process is useful for constructing dynamic messages, file paths, or command arguments within shell scripts.

Introduction

Concatenation is the process of appending one string to the end of another. In shell scripting, this can be achieved using various methods, such as simple variable expansion, command substitution, or using the printf command.

Methods of Concatenation

1. Using Simple Variable Expansion

You can concatenate variables simply by placing them adjacent to each other without any space. For example:

first_name="John"
last_name="Doe"
full_name="$first_name$last_name"
echo "Full name: $full_name"

2. Using Command Substitution

Command substitution allows you to use the output of a command as part of a string. For example:

current_date=$(date +%Y-%m-%d)
file_name="logfile_$current_date.txt"
echo "Log file name: $file_name"

3. Using printf Command

The printf command provides more control over formatting and concatenation. For example:

first_name="John"
last_name="Doe"
printf "Full name: %s %s\n" "$first_name" "$last_name"

Best Practices

  • Ensure proper quoting to handle spaces and special characters.
  • Use meaningful variable names for clarity and maintainability.
  • Consider using printf for more complex formatting requirements.

Conclusion

Concatenating variables in Linux shell scripting is a fundamental task for building dynamic and versatile scripts. By mastering the various methods of concatenation, you can create powerful scripts to automate tasks efficiently.

⬅️Previous-----------Next ➡️

Table of contents 🚀