Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: need to strip single quotes around a string

Tags:

bash

Following is the code snippet from my bash script:

....
....
for ((i=0; i<${#abc[@]}; i++))
  do
    xyz=${abc[i]}
....
....

When the value of 'xyz' is substituted in the script, the value has single quotes around it:

'"6b76cdae-a4a8-4e88-989d-1581ae2d5b98"'

Why are the single quotes added and how do I strip them?

Thanks!

like image 807
Maddy Avatar asked Jan 06 '15 06:01

Maddy


People also ask

Can you use single quotes in bash?

3.1. 2.2 Single QuotesEnclosing characters in single quotes (' ' ') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

Can the value of a string be surrounded by single quotes?

Enclosing characters in single quotes preserves the literal value of each character within the quotes.


2 Answers

You can replace

xyz=${abc[i]}

with

eval xyz=${abc[i]}

And here is an illustrating example what happens:

$ foo="'"'"bar"'"'"
$ echo $foo
'"bar"'
$ eval foo=$foo
$ echo $foo
"bar"
$ eval foo=$foo
$ echo $foo
bar

So, what happens with the holy eval is that the assignment gets split into two parts:

  1. Evaluate $abc
  2. Assign to $xyz

instead of just Step 2.

Maybe in your case you should consider to already change the assignment of abc but i don't know because of ignorance ;)

like image 169
nino_mezza Avatar answered Nov 05 '22 05:11

nino_mezza


You can try to remove all single quotes in array abc with Parameter Expansion:

abc=(${abc[@]//\'/})

You can try to remove all single quotes in string xyz with Parameter Expansion:

xyz=${xyz//\'/}
like image 34
Cyrus Avatar answered Nov 05 '22 05:11

Cyrus