0
0
Bash Scriptingscripting~5 mins

String variables in Bash Scripting

Choose your learning style9 modes available
Introduction
String variables let you store words or sentences to use later in your script.
To save a user's name and greet them.
To hold a file path for easy reuse.
To keep a message that you want to print multiple times.
To store command output for processing.
To build a sentence from smaller parts.
Syntax
Bash Scripting
variable_name="your text here"
Use double quotes to keep spaces and special characters intact.
No spaces around the equal sign (=) when assigning.
Examples
Stores the word Alice in the variable named 'name'.
Bash Scripting
name="Alice"
Stores a full sentence with punctuation.
Bash Scripting
greeting="Hello, world!"
Stores a file path as a string.
Bash Scripting
path="/home/user/docs"
Sample Program
This script stores a name and then creates a greeting using that name. It prints the greeting.
Bash Scripting
#!/bin/bash

name="Bob"
greeting="Hello, $name!"
echo "$greeting"
OutputSuccess
Important Notes
To use the value of a string variable, prefix it with a dollar sign ($).
Always quote variables when using them to avoid word splitting or globbing.
Variable names should only contain letters, numbers, and underscores, and cannot start with a number.
Summary
String variables store text for reuse in scripts.
Assign strings with no spaces around = and use quotes.
Use $variable_name to access the stored text.