Syntax error unexpected end and premature end of file

Помогите пожалуйста, не работает скрипт немогу понять в чем проблема, выбрасивает ошибку - syntax error, unexpected end of file. $arResult -...

За последние 24 часа нас посетили 11584 программиста и 1164 робота. Сейчас ищут 309 программистов …


  1. Peter98

    С нами с:
    26 дек 2017
    Сообщения:
    2
    Симпатии:
    0

    Помогите пожалуйста, не работает скрипт немогу понять в чем проблема, выбрасивает ошибку — syntax error, unexpected end of file. $arResult — многовимерний масив.

    1. <?function build_tree($arResult,$previousLevel = 0){?>
    2. <?foreach($arResult as $arItem):?>
    3.     <?if ($previousLevel && $arItem[«DEPTH_LEVEL»] < $previousLevel):?>
    4.         <?=str_repeat(«</ul></li>», ($previousLevel $arItem[«DEPTH_LEVEL»]));?>
    5.     <?if ($arItem[«IS_PARENT»]):?>
    6.         <?if ($arItem[«DEPTH_LEVEL»] == 1):?>              
    7.             <li class=»open current»><span class=»sb_showchild»></span><a href=»<?=$arItem[«LINK»]?>«><span><?=$arItem[«TEXT»]?></span></a>
    8.                     <?build_tree($arResult[‘CHILDRENS’])?>
    9.             <li><a href=»<?=$arItem[«LINK»]?>«><?=$arItem[«TEXT»]?></a>
    10.                     <?build_tree($arResult[‘CHILDRENS’])?>
    11.         <?if ($arItem[«PERMISSION»] > «D»):?>
    12.             <?if ($arItem[«DEPTH_LEVEL»] == 1):?>
    13.                 <li class=»close»><a href=»<?=$arItem[«LINK»]?>«><span><?=$arItem[«TEXT»]?></span></a></li>
    14.                 <li><a href=»<?=$arItem[«LINK»]?>«><?=$arItem[«TEXT»]?></a></li>
    15.     <?$previousLevel = $arItem[«DEPTH_LEVEL»];?>
    16. <?if ($previousLevel > 1)://close last item tags?>
    17.     <?=str_repeat(«</ul></li>», ($previousLevel1) );?>
    18. <?if (!empty($arResult)):?>
    19. <?build_tree($arResult);?>


  2. Maputo

    Maputo
    Активный пользователь

    С нами с:
    30 июл 2015
    Сообщения:
    1.136
    Симпатии:
    173


  3. Sergey_Tsarev

    Sergey_Tsarev
    Активный пользователь

    С нами с:
    17 мар 2016
    Сообщения:
    502
    Симпатии:
    105

    @Peter98
    Вот так перепиши:

    1. <?if ($previousLevel > 1):/*close last item tags*/?>


  4. Sail

    С нами с:
    1 ноя 2016
    Сообщения:
    1.524
    Симпатии:
    345

    @Peter98, комментарий в 35-й строке тут, однако, ни при чём.
    А вот хвост в 38-й — отчего он?
    И хоть визуально упорядочить код не помешало бы… Короткие теги <? заменить на <?php (не трогая те, что <?=)
    Несколько идущих подряд строк <? кодphp ?> объединить… в один тег <?php кодphp ?>
    И убрать ?> в конце файла (если файл завершается кодом php)


  5. Sergey_Tsarev

    Sergey_Tsarev
    Активный пользователь

    С нами с:
    17 мар 2016
    Сообщения:
    502
    Симпатии:
    105

    Вот так удобнее мне кажется читать код:

    1. function build_tree($arResult, $previousLevel = 0) {
    2.     foreach ($arResult as $arItem) {
    3.         if ($previousLevel && $arItem[«DEPTH_LEVEL»] < $previousLevel) {
    4.             echo str_repeat(«</ul></li>», ($previousLevel $arItem[«DEPTH_LEVEL»]));
    5.         if ($arItem[«IS_PARENT»]) {
    6.             if ($arItem[«DEPTH_LEVEL»] == 1) {
    7.                 echo ‘<li class=»open current»><span class=»sb_showchild»></span><a href=»‘ . $arItem[«LINK»] . ‘»><span>’ . $arItem[«TEXT»] . ‘</span></a><ul>’;
    8.                 build_tree($arResult[‘CHILDRENS’]);
    9.                 echo ‘<li><a href=»‘ . $arItem[«LINK»] . ‘»>’ . $arItem[«TEXT»] . ‘</a><ul>’;
    10.                 build_tree($arResult[‘CHILDRENS’]);
    11.             if ($arItem[«PERMISSION»] > «D») {
    12.                 if ($arItem[«DEPTH_LEVEL»] == 1) {
    13.                     echo ‘<li class=»close»><a href=»‘ . $arItem[«LINK»] . ‘»><span>’ . $arItem[«TEXT»] . ‘</span></a></li>’;
    14.                     echo ‘<li><a href=»‘ . $arItem[«LINK»] . ‘»>’ . $arItem[«TEXT»] . ‘</a></li>’;
    15.         $previousLevel = $arItem[«DEPTH_LEVEL»];
    16.     if ($previousLevel > 1) { //close last item tags
    17.         echo str_repeat(«</ul></li>», ($previousLevel 1));
    18.     echo ‘<div class=»sb_nav»><ul>’;


  6. Sergey_Tsarev

    Sergey_Tsarev
    Активный пользователь

    С нами с:
    17 мар 2016
    Сообщения:
    502
    Симпатии:
    105

    Само собой. Но то, что у ТС написано читать невозможно. Каждый пук в отдельной php-теге.


  7. Avenax

    С нами с:
    27 июн 2016
    Сообщения:
    7
    Симпатии:
    0

    пхп состоит из типов данных


  8. [vs]

    Команда форума
    Модератор

    С нами с:
    27 сен 2007
    Сообщения:
    10.534
    Симпатии:
    623

    серьезно, то есть что закомментирован закрывающий дескриптор ?> и поэтому он не работает — это не важно?

    если ты удалял комментарий вместе с ?> то конечно ничего не работало, ведь это та же самая ситуация.


  9. [vs]

    Команда форума
    Модератор

    С нами с:
    27 сен 2007
    Сообщения:
    10.534
    Симпатии:
    623

    @Sail надо же и правда, ?> игнорируется только в комментариях в стиле /* */.

@RehabMan

DefinitionBlock ("TEST.aml", "DSDT", 2, "FU", "BAR", 0x00000001)
{
    Device(BLAH)
    {
        Name(X, 0)
        Method (TEST, 2, NotSerialized)
        {
            If (LNotEqual (And (X, 0x03, Local1), Zero))
            {
            }
        }
     }
}

The above code compiles correctly (old school).

Then disassembles as (C-style):

DefinitionBlock ("test.aml", "DSDT", 2, "FU", "BAR", 0x00000001)
{
    Device (BLAH)
    {
        Name (X, Zero)
        Method (TEST, 2, NotSerialized)
        {
            If ((Local1 = (X & 0x03) != Zero)) {}
        }
    }
}

Note: misplaced parentheses.

Correct disassembly:

DefinitionBlock ("test.aml", "DSDT", 2, "FU", "BAR", 0x00000001)
{
    Device (BLAH)
    {
        Name (X, Zero)
        Method (TEST, 2, NotSerialized)
        {
            If ((Local1 = (X & 0x03)) != Zero) {}
        }
    }
}

But it also does not compile.

Results in errors:

test.dsl      8:             If ((Local1 = (X & 0x03)) != Zero) {}
Error    6126 -        syntax error, unexpected ')' ^ 

test.dsl     11: 
Error    6126 - syntax error, unexpected '}', expecting $end and premature End-Of-File

ASL Input:     test.dsl - 11 lines, 231 bytes, 7 keywords

Compilation complete. 2 Errors, 0 Warnings, 0 Remarks, 0 Optimizations

@acpibob

We just fixed this one today, will double-check with your code before checkin.

From: RehabMan [mailto:notifications@github.com]
Sent: Thursday, October 30, 2014 2:00 PM
To: acpica/acpica
Subject: [acpica] Assignment within If, causes error upon disassembly with C-style (#58)

DefinitionBlock («TEST.aml», «DSDT», 2, «FU», «BAR», 0x00000001)

{

Device(BLAH)

{

    Name(X, 0)

    Method (TEST, 2, NotSerialized)

    {

        If (LNotEqual (And (X, 0x03, Local1), Zero))

        {

        }

    }

 }

}

The above code compiles correctly (old school).

Then disassembles as (C-style):

DefinitionBlock («test.aml», «DSDT», 2, «FU», «BAR», 0x00000001)

{

Device (BLAH)

{

    Name (X, Zero)

    Method (TEST, 2, NotSerialized)

    {

        If ((Local1 = (X & 0x03) != Zero)) {}

    }

}

}

Note: misplaced parentheses.

Correct disassembly:

DefinitionBlock («test.aml», «DSDT», 2, «FU», «BAR», 0x00000001)

{

Device (BLAH)

{

    Name (X, Zero)

    Method (TEST, 2, NotSerialized)

    {

        If ((Local1 = (X & 0x03)) != Zero) {}

    }

}

}

But it also does not compile.

Results in errors:

test.dsl 8: If ((Local1 = (X & 0x03)) != Zero) {}

Error 6126 — syntax error, unexpected ‘)’ ^

test.dsl 11:

Error 6126 — syntax error, unexpected ‘}’, expecting $end and premature End-Of-File

ASL Input: test.dsl — 11 lines, 231 bytes, 7 keywords

Compilation complete. 2 Errors, 0 Warnings, 0 Remarks, 0 Optimizations


Reply to this email directly or view it on GitHubhttps://github.com//issues/58.

@acpibob

Now compiles—>disassembles—> compiles correctly.

Will checkin the code tomorrow.

From: RehabMan [mailto:notifications@github.com]
Sent: Thursday, October 30, 2014 2:00 PM
To: acpica/acpica
Subject: [acpica] Assignment within If, causes error upon disassembly with C-style (#58)

DefinitionBlock («TEST.aml», «DSDT», 2, «FU», «BAR», 0x00000001)

{

Device(BLAH)

{

    Name(X, 0)

    Method (TEST, 2, NotSerialized)

    {

        If (LNotEqual (And (X, 0x03, Local1), Zero))

        {

        }

    }

 }

}

The above code compiles correctly (old school).

Then disassembles as (C-style):

DefinitionBlock («test.aml», «DSDT», 2, «FU», «BAR», 0x00000001)

{

Device (BLAH)

{

    Name (X, Zero)

    Method (TEST, 2, NotSerialized)

    {

        If ((Local1 = (X & 0x03) != Zero)) {}

    }

}

}

Note: misplaced parentheses.

Correct disassembly:

DefinitionBlock («test.aml», «DSDT», 2, «FU», «BAR», 0x00000001)

{

Device (BLAH)

{

    Name (X, Zero)

    Method (TEST, 2, NotSerialized)

    {

        If ((Local1 = (X & 0x03)) != Zero) {}

    }

}

}

But it also does not compile.

Results in errors:

test.dsl 8: If ((Local1 = (X & 0x03)) != Zero) {}

Error 6126 — syntax error, unexpected ‘)’ ^

test.dsl 11:

Error 6126 — syntax error, unexpected ‘}’, expecting $end and premature End-Of-File

ASL Input: test.dsl — 11 lines, 231 bytes, 7 keywords

Compilation complete. 2 Errors, 0 Warnings, 0 Remarks, 0 Optimizations


Reply to this email directly or view it on GitHubhttps://github.com//issues/58.

@acpibob

Works now with the current tree head.

@RehabMan

You are running a Bash script, and you see a syntax error: Unexpected end of file.

What does it mean?

This can happen if you create your script using Windows.

Why?

Because Windows uses a combination of two characters, Carriage Return and Line Feed, as line break in text files (also known as CRLF).

On the other side Unix (or Linux) only use the Line Feed character as line break.

So, let’s see what happens if we save a script using Windows and then we execute it in Linux.

Using the Windows notepad I have created a Bash script called end_of_file.sh:

#/bin/bash

if [ $# -gt 0 ]; then
  echo "More than one argument passed"
else
  echo "No arguments passed"
fi

And here is the output I get when I execute it:

[ec2-user@localhost scripts]$ ./end_of_file.sh 
./end_of_file.sh: line 2: $'r': command not found
./end_of_file.sh: line 8: syntax error: unexpected end of file 

How do we see where the problem is?

Edit the script with the vim editor using the -b flag that runs the editor in binary mode:

[ec2-user@localhost scripts]$ vim -b end_of_file.sh

(Below you can see the content of the script)

#/bin/bash^M
^M
if [ $# -gt 0 ]; then^M
  echo "More than one argument passed"^M
else^M
  echo "No arguments passed"^M
fi^M

At the end of each line we see the ^M character. What is that?

It’s the carriage return we have mentioned before. Used by Windows but not by Unix (Linux) in line breaks.

To solve both errors we need to convert our script into a format that Linux understands.

The most common tool to do that is called dos2unix.

If dos2unix is not present on your system you can use the package manager of your distribution to install it.

For instance, on my server I can use YUM (Yellowdog Updater Modified).

To search for the package I use the yum search command:

[root@localhost ~]$ yum search dos2unix
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
====================== N/S matched: dos2unix =====================================
dos2unix.x86_64 : Text file format converters

And then the yum install command to install it:

[root@localhost ~]$ yum install dos2unix
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
amzn2-core                                                   | 2.4 kB  00:00:00
amzn2extra-docker                                            | 1.8 kB  00:00:00     
Resolving Dependencies
--> Running transaction check
---> Package dos2unix.x86_64 0:6.0.3-7.amzn2.0.2 will be installed
--> Finished Dependency Resolution 

Dependencies Resolved 

==================================================================================
  Package       Arch        Version            Repository            Size
==================================================================================
 Installing:
  dos2unix      x86_64      6.0.3-7.amzn2.0.2  amzn2-core            75 k
 
 Transaction Summary
==================================================================================
 Install  1 Package

 Total download size: 75 k
 Installed size: 194 k
 Is this ok [y/d/N]: y
 Downloading packages:
 dos2unix-6.0.3-7.amzn2.0.2.x86_64.rpm                      |  75 kB  00:00:00     
 Running transaction check
 Running transaction test
 Transaction test succeeded
 Running transaction
   Installing : dos2unix-6.0.3-7.amzn2.0.2.x86_64                          1/1 
   Verifying  : dos2unix-6.0.3-7.amzn2.0.2.x86_64                          1/1 

 Installed:
   dos2unix.x86_64 0:6.0.3-7.amzn2.0.2                                                                                                                         
 Complete! 

We are ready to convert our script using dos2unix!

[ec2-user@localhost scripts]$ dos2unix end_of_file.sh 
dos2unix: converting file end_of_file.sh to Unix format ... 

And now it’s time to execute it:

[ec2-user@localhost scripts]$ ./end_of_file.sh  No arguments passed

It works!

If you are interested I have written an article that explains the basics of Bash script arguments.

Conclusion

I have found myself having to use the dos2unix command several times over the years.

And now you know what to do if you see the syntax error “Unexpected end of file” while running a Bash script 🙂


Related FREE Course: Decipher Bash Scripting

Related posts:

I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!

Понравилась статья? Поделить с друзьями:
  • Syntax error unexpected character after line continuation character
  • Syntax error unexpected bash array
  • Syntax error the requested module dell does not provide an export named default
  • Syntax error python что это
  • Syntax error python примеры