sachinpkale
sachinpkale

Reputation: 999

linux shell script: Ignore double quotes from IFS

Due to the default value of IFS, I am getting following result.

STR="this is a \"valid string\""
for a in $STR; do
  echo $a;
done

will give output as:

this
is
a
"valid
string"

But I don't want to split "valid string". I need output as:

this
is
a
"valid string"

So, how can I make shell ignore double quotes from IFS?

Upvotes: 0

Views: 1488

Answers (2)

l0b0
l0b0

Reputation: 58908

There are two types of quotes: Literal ones, and syntactic ones. The outer quotes of STR are syntactic, which means that they are not actually part of the string, they are just used to tell Bash where the string starts and ends. The inner (escaped) quotes are literal, so they are part of the string. In other words, the literal value of your string is:

this is a "valid string"

Now if you want to loop over this, you have to remember that this string consists of five (space-separated) literal words:

this
is
a
"valid
string"

If you want to get around this, one you can either use eval (but beware of the serious security issues) or arrays:

declare -a STR=(this is a "valid string")
for str in "${STR[@]}"
do
    echo "$str"
done

Upvotes: 2

Roland Illig
Roland Illig

Reputation: 41676

That's not easily possible. You could switch to Perl instead. Or, if you have full control over the string, and nobody can possibly ever insert something evil into it, you could use this code:

str="a b c \"d e\""
eval "set args $str; shift"

for i in "$@"; do
  echo "$i"
done

This will output the last word without the quotes, though. And it overwrites the command lune arguments to the shell program itself.

If you need to keep the quotes, this is called parsing and should not be done by a shell program, since it becomes too complicated.

Upvotes: 0

Related Questions