0
0
Bash Scriptingscripting~5 mins

Single quotes (literal strings) in Bash Scripting

Choose your learning style9 modes available
Introduction
Single quotes let you write text exactly as it is, without any changes or special meanings.
When you want to print a message exactly as you typed it.
When your text has special characters like $ or \ that you don't want to be treated specially.
When you want to store a fixed string in a variable without any substitutions.
When you want to avoid accidental command or variable expansions inside your text.
Syntax
Bash Scripting
echo 'your text here'
Text inside single quotes is taken exactly as written, no variables or commands run inside.
You cannot put a single quote inside single quotes directly; you need tricks to do that.
Examples
Prints the exact text Hello, world! without any changes.
Bash Scripting
echo 'Hello, world!'
Prints My name is $name literally, not My name is John.
Bash Scripting
name=John
 echo 'My name is $name'
Shows that $ and backslash are not treated specially inside single quotes.
Bash Scripting
echo 'Special chars like $ and \\ stay as is'
Sample Program
Shows how to store and print a string with a single quote inside using escaping and closing/reopening single quotes.
Bash Scripting
#!/bin/bash

message='It'\''s a sunny day!'
echo "$message"

literal='It'\''s a sunny day!'
echo "$literal"
OutputSuccess
Important Notes
Inside single quotes, everything is literal except you cannot directly include a single quote.
To include a single quote inside single quotes, close the quotes, add an escaped single quote, then reopen the quotes: 'It'\''s'.
Double quotes allow variable expansion, but single quotes do not.
Summary
Single quotes keep text exactly as you write it.
No variables or commands run inside single quotes.
Use special tricks to include single quotes inside single-quoted text.