Why am I not able to execute this bash script using php? I have tried exec() as well as shell_exec().


$old = getcwd();
echo $old;


echo "i am a" > /opt/lampp/htdocs/a.txt
echo "Done"

I have tried chdir as suggested here, as well as I have checked my disable_functions in php.ini, it doesn't have anything. I have also checked other questions, but none seem to solve my problem.

  • 1. Why don't you give the full path to the script? 2. Why are you doing chdir($old) twice? Is that a typo?
    – muru
    Sep 5, 2014 at 17:15
  • I have tried that too. But echoing $old shows the correct path of a.sh. As index.php and a.sh are in the same dir. chdir was there because I copied that from somewhere, then edited the 1st chdir but not the second. Sep 5, 2014 at 17:28
  • 1
    Alright, what do the apache logs say? Any mention of an error?
    – muru
    Sep 5, 2014 at 17:33
  • 1
    Does a.sh have #!/bin/bash as the first line? Have you tried exec("/bin/bash a.sh")
    – Dan
    Sep 5, 2014 at 17:35
  • 1
    Aha did not see that BUT you need a leading slash before bin so it reads #!/bin/bash
    – Dan
    Sep 5, 2014 at 17:44

1 Answer 1


First, be sure that the shebang is exactly as follow:


Second, be sure that the script is executable using the following command in terminal:

chmod +x /path/to/a.sh

And third, you must to use the full path for the bash script, or in your case, you can use:


And, as an aside note, the following two commands from your php script have no sense:

$old = getcwd();

They are equivalent with chdir(getcwd()), which change the current directory to ...the current directory, so in fact, nothing happens.

  • 2
    @OptimusPrime Well, check again, you said in your Q that your bash script starts with #!bin/bash, not #!/bin/bash as I said which obviously are not the same Sep 5, 2014 at 17:47
  • Sorry about previous comment. I did not see that clearly. I have made the file executable. But it still does not write that file a.txt. What else may be the problem? Sep 5, 2014 at 17:51
  • 1
    Permissions problem, plenty of info on this site and around the web.
    – Dan
    Sep 5, 2014 at 17:54
  • @RaduRădeanu Yes, I realize they have no effect. But I just copied that from web, and was trying them if they could solve the problem. Sep 5, 2014 at 17:59
  • 1
    @dan08 Yes, I changed the permissions and it worked. You were right again. Sep 5, 2014 at 17:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .