11

How to insert a quote at the start and end into a string variable?

I have this variable say:

string="desktop/first folder" 

If I echo this, it will display:

desktop/first folder 

I need the string to be stored as:

"desktop/first folder" 
1
  • I know the question is about bash but for POSIX compatible system where the string must contain both single and double quotes you have to mix between both without spaces in between. For example string="single quote: ' double quote: "'"'" end of string". This works because quoted strings next to each other are considered a single string and you can switch between single and double quote strings within those parts. Commented Jul 10, 2022 at 18:04

5 Answers 5

9

If you don't do variable substitution, using single quotes as delimiters, so you can use double quotes in your string:

string='"desktop/first folder"' 
15

In bash you can use \ as an escape character what whatever follows it. In your case, use it like this:

string="\"desktop/first folder\"" 
3

In the case one needs to do variable substitution:

string='"'"$folder"'"' 

The inner double quotes allow variable expansion, and each of the outer double quote is flanked by single quotes to "keep" them at their place.

1

You could also use ANSI C-style quoting if you need both single and double quotes or other special characters:

$ echo $'"desktop/first folder"' "desktop/first folder" 
$ echo $'\'desktop/first folder\'' 'desktop/first folder' 
$ echo $'"desktop/first folder"\n"desktop/second folder"' "desktop/first folder" "desktop/second folder" 
1

If you want to store a string in Bash with literal double qoutes, the approach is simple and safe. Here's the cleanest way:

string="desktop/first folder" quoted_string="\"$string\"" echo "$quoted_string" 

"\ --> escaping double qoute to be part of our string value.

Another solution using printf

printf is safer with strings.

string="desktop/first folder" quoted_string=$(printf '"%s"' "$string") echo "$quoted_string" 
  • %s to printf means: print value of variable ($string in our case) without changes

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.