Prajwal Koirala
Prajwal Koirala

Reputation: 83

how do i have quotes inside of a echo?

I need some help. I am trying to do something like this

echo "{
    "server":"$SERVER_HOST",
    "server_port":"$SERVER_PORT",
    "password":"$PASSWORD_CHOICE",
    "timeout":$TIMEOUT_CHOICE
}" >> /etc/ss/example.json

and i need the output like

{
    "server":"127.0.0.1",
    "server_port":80,
    "password":"randompassword",
    "timeout":60
}

but the output is always like

{
    server:127.0.0.1,
    server_port:80,
    password:randompassword,
    timeout:60
}

Upvotes: 2

Views: 552

Answers (3)

Luis Colorado
Luis Colorado

Reputation: 12698

you have two approaches:

  • The first, already answered in other responses, is to use the other quotes (if you have used ', then use ", or viceversa) but you normally lose the possibility of interpreting shell variables, if you use ' externally.
  • The second, is to get out of quotes, and use escape \\ character to escape the shell interpretation, as in
  • The approach commented in some responses, of using the escape character inside quotes, normally gives not good results (depending on the used shell, escapes don't work inside single quotes, or even inside double quotes) The best is to exit from quotes, escape, and get in quotes again, as shown below.
  • The approach of using cat(1) and in-flow redirecting input with << is shell dependant (not all shells allow this, so you have to be carefull)
echo "{
    "\""server"\"":"\""$SERVER_HOST"\"",
    "\""server_port"\"":"\""$SERVER_PORT"\"",
    "\""password"\"":"\""$PASSWORD_CHOICE"\"",
    "\""timeout"\"":$TIMEOUT_CHOICE
}" >> /etc/ss/example.json

you have just to convert each " inside the string into "\"" (if you have used double quotes to quote your string). The same also works for single quotes (in case you have used single quotes to quote your string), converting each ' into '\''.

Upvotes: 0

user1934428
user1934428

Reputation: 22291

Don't use echo, but cat with a here-document:

cat >> /etc/ss/example.json <<EOF
{
  "server":"$SERVER_HOST",
  "server_port":"$SERVER_PORT",
  "password":"$PASSWORD_CHOICE",
  "timeout":$TIMEOUT_CHOICE
}
EOF

Upvotes: 2

Akbar30bill
Akbar30bill

Reputation: 362

use backslash to put special characters like \" or \n for nextline or \t for tab

echo "this is my quotes -> \" <-"

the out put will be

this is my quotes -> " <-

Upvotes: 1

Related Questions