SoFunction
Updated on 2025-03-10

A brief analysis of the difference between single quotes and double quotes in shell script strings

1. Basic knowledge of strings

Strings are the most commonly used and useful data types in shell programming (except numbers and strings, there are no other types that are easy to use). Strings can be in single quotes, double quotes, or without quotes. The difference between odd and double quotes is similar to PHP.

Single quotes

Copy the codeThe code is as follows:

str='this is a string'

Limitations of single quote strings:

•Any character in single quotes will be output as it is, and variables in single quotes strings are invalid;
•Single quotes cannot appear in single quote strings (not after using escape characters for single quotes).

Double quotes

Copy the codeThe code is as follows:

your_name='qinjx'
str="Hello, I know your are \"$your_name\"! \n"

Advantages of double quotes:

•There can be variables in double quotes
•Escape characters can appear in double quotes

2. Commonly used string related methods

Stitching strings

Copy the codeThe code is as follows:

your_name="qinjx"
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"

echo $greeting $greeting_1

Get the string length

Copy the codeThe code is as follows:

string="abcd"
echo ${#string} #Output 4

Extract substrings

Copy the codeThe code is as follows:

string="alibaba is a great company"
echo ${string:1:4} #output liba

Find substrings

Copy the codeThe code is as follows:

string="alibaba is a great company"
echo `expr index "$string" is`

For more string processing methods, please refer to:https://:81/article/