开发者

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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜