When adding the line:
#!/usr/bin/env drush
to the top of a PHP script to automatically run using drush, the variable __DIR__
and __FILE__
stop returning my script file name and directory and return drush paths instead.
Is there another variable that should be used in case of drush scripts to get the script path and dir?
Note: When I remove that line and use drush scr <myscript>
instead, __DIR__
and __FILE__
return the correct paths.
[EDIT]
To test the suggestions below in the answer by Hasan Bayat:
I ran the following script:
<?php
print('__DIR__ value is: '.__DIR__."\n");
print('__FILE__ value is: '.__FILE__."\n");
print('SCRIPT_FILENAME is: '.$_SERVER['SCRIPT_FILENAME']."\n");
print('PATH_TRANSLATED is: '.$_SERVER['PATH_TRANSLATED']."\n");
print('from backtrace: '.debug_backtrace()[count(debug_backtrace()) - 1]['file']."\n");
print('included_files: '.get_included_files()[0]."\n");
Using the command line:
drush scr script.php
And the results are as following
__DIR__ value is: /path/to/my/script
__FILE__ value is: /path/to/my/script/script.php
SCRIPT_FILENAME is: /path/to/current/dir/index.php
PATH_TRANSLATED is: /usr/local/bin/drush
from backtrace: /usr/local/bin/drush
included_files: /usr/local/bin/drush
I then changed the script to add the line #!/usr/bin/env drush
at the top. And reran the script this time with the command:
./script.php
Now the results are as following:
__DIR__ value is: phar:///usr/local/bin/drush/commands/core
__FILE__ value is: phar:///usr/local/bin/drush/commands/core/core.drush.inc(1194) : eval()'d code
SCRIPT_FILENAME is: /path/to/current/dir/index.php
PATH_TRANSLATED is: /usr/local/bin/drush
from backtrace: /usr/local/bin/drush
included_files: /usr/local/bin/drush
So apparently none of the suggested solutions works in case the drush first line is added to the script.