LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   for loop error.... (https://www.linuxquestions.org/questions/linux-newbie-8/for-loop-error-789369/)

lipun4u 02-15-2010 11:15 PM

for loop error....
 
Conider the following code..

1 #!/bin/bash
2
3 for tst in I don't know if this'll work
4 do
5 echo "word :: $tst"
6 done

Why the o/p is so amgious ?

word :: I
word :: dont know if thisll
word :: work

bigrigdriver 02-15-2010 11:22 PM

Quote:

for tst in I don't know if this'll work
The single quotes in don't and this'll constitute a single quoted phrase withing quotes which prevent the shell from parsing the phrase.

Try this instead:
for tst in I don\'t know if this\'ll work

using the backslash to escape the single quotes.

word :: I
word :: don't
word :: know
word :: if
word :: this'll
word :: work

lipun4u 02-15-2010 11:35 PM

I know .... but why the op is so illogical ??

chrism01 02-16-2010 12:17 AM

Quote:

Use double quotes to prevent word splitting. [3] An argument enclosed in double quotes presents itself as a single word, even if it contains whitespace separators.
http://www.linuxtopia.org/online_boo...uotingvar.html

Just about all programming langs have an equivalent (often the same) rule to allow 'values' to have spaces or other (normally) special chars in them.

colucix 02-16-2010 05:03 AM

Quote:

Originally Posted by lipun4u (Post 3865168)
I know .... but why the op is so illogical ??

Actually it's quite logical. The shell interpret the string
Code:

I don't know if this'll work
as
Code:

I dont know if thisll work
where the part in red is not split into fields (due to the single quotes, as already mentioned). The string concatenation do the rest.

The blank spaces that actually act as field separators are shown here:
Code:

I dont know if thisll work
 ^                  ^



All times are GMT -5. The time now is 10:16 PM.