7

Is there way of inserting 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"
Ali Gul
  • 73
  • 1
  • 1
  • 3
  • 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. – Mikko Rantalainen Jul 10 '22 at 18:04

3 Answers3

13

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

string="\"desktop/first folder\""
undo
  • 5,961
  • 8
  • 41
  • 61
jcbermu
  • 17,278
  • 2
  • 52
  • 60
7

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"'
xenoid
  • 9,782
  • 4
  • 20
  • 31
1

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.

jorvaor
  • 11
  • 2