|
Quoting in shell scripts controls how special characters are interpreted. Understanding quoting is essential for writing correct shell scripts. There are three types of quoting: single quotes, double quotes, and backslash escaping. Single quotes can be used if there are no variables to expand or if there are no special characters you need to escape. Use single quotes when you want literal text with no interpretation of special characters. You can embed single quotes in singly quoted strings by enclosing the escaped single quote with single quotes. |
|
|
Output:
Hello, world! Hello, $name! Backslashes are literal: \n \t Multiple backslashes (4): \\\\ Escaped single quote: ' |
|
|
Double quotes are needed when strings contain variables that need to be expanded or special characters you may want to escape. A good use case is when you want to have double quotes in a string as well as variable expansion. You can embed double quotes in doubly quoted strings by escaping the double quote with a backslash. Please also note the difference between echo and printf. |
|
|
Output:
Hello, world! Hello, "world"! Backslashes are literal here as well: \n \t more content after the escape sequences Backslashes are literal here as well: more content after the escape sequences Multiple backslashes (2): \\ Escaped double quote: " |
|
|
The backslash escapes single characters. In this example, we escape the double quote, the backslash, and the dollar sign. |
|
|
Output:
She said "Hello" Path: C:\Users\name Dollar sign: $100 |
|
|
You can mix quoting styles in the same string. If the outer quotes are double quotes, the inner quotes can be single quotes without escaping. If the outer quotes are single quotes, the inner quotes can be double quotes without escaping. In this example, we use double quotes for the outer quotes and single quotes for the inner quotes. |
|
|
Output:
It's a World Say "Hello" |
|
|
Without quotes, the shell splits on spaces. This is called word splitting. |
|
|
Output:
Without quotes: file1.txt file2.txt file3.txt With quotes: file1.txt file2.txt file3.txt |
|
|
Escape sequences like |
|
|
Output:
Line 1\nLine 2 Tab:\tseparated Line 1 Line 2 |
|