Shell Variable Management and Assignment Techniques
Variable Definition
In Bash shell environments, all variable values are stored as strings regarrdless of whether quotes are used during assignment. This means Bash does not perform type differentiation by default - integers and decimals become string values, differing from most programming languages.
Three Methods for Variable Declaration
| Syntax | Description | Usage Context | Example |
|---|---|---|---|
var_name=value |
Direct assignment without quotes | When value contains no whitespace characters | website=http://example.comecho $website |
var_name='value' |
Single quote enclosure | When value includes whitespace | title='My Blog Title'echo $title |
var_name="value" |
Double quote enclosure | Similar to single quotes but allows interpolation | greeting="Hello $USER"echo $greeting |
Variable naming conventions follow standard programming practices:
- Names consist of digits, letters, and underscores
- Must begin with a letter or underscore
- Cannot use reserved shell keywords (view with
helpcommand)
Quote Behavior Differences
Single quotes preserve literal content - variables and commands remain unparsed:
base_url="https://example.com"
output1='Visit ${base_url}'
output2="Visit ${base_url}"
echo $output1 # Output: Visit ${base_url}
echo $output2 # Output: Visit https://example.com
Variable Usage
Access defined variables by prefixing the name with the dollar sign $. Curly braces {} around variable names are optional but recommended for clarity and boundary identification.
programmer="John Doe"
echo $programmer
echo ${programmer}
tool="Python"
echo "Expert in ${tool} development"
Without braces in complex contexts like echo "Expert in $tooldevelopment", the interpreter treats $tooldevelopment as a single variable name.
Modifying Variable Values
Reassign new values to existing variables by referencing the variable name without the dollar prefix:
address="https://example.com"
echo ${address}
address="https://example.com/api/"
echo ${address}
The dollar sign $ should only appear when accessing variable values, never during reassignment.
Command Result Assignment
Capture command outputs in variables using thece approaches:
- Backtick method:
result_var=command`` - Modern syntax:
result_var=$(command)
Example reading file contents:
data=`cat readme.md`
content=$(cat readme.md)
echo 'Data:',${data}
echo 'Content:',${content}
Read-Only Variables
Create immutable variables using the readonly command:
#!/bin/bash
site_address="https://secure.example.com"
readonly site_address
site_address="https://new.example.com" # This will fail
Attempting modification produces: bash: site_address: This variable is read only.
Variable Removal
Delete variables with the unset command followed by the variable name: unset variable_name. Once deleted, variables become inaccessible. Note that unset cannot remove read-only variables.