in reply to Re: cd in perl not working?
in thread cd in perl not working?

Amen. Years later and this is still a very useful post. I don't know what the difference is, but this method: print <<`ShellOut`; ... ShellOut was the only way I could get this to work. Never had a problem before, but I just set up a new CentOS machine, tried to run some shell commands using "system" or just backticks, and it would not work. The lack of a persistent session issue is duly noted -- that was ONE of my issues, but even once I realized that a "cd" in one "system" command did not apply to the next "system" command, it would not work correctly. Again, I don't know why the above method does work when the others do not, but I am not going to dwell on it - I just wanted it to work. Thank you.

Replies are listed 'Best First'.
Re^3: cd in perl not working?
by Bethany (Scribe) on Aug 13, 2014 at 03:53 UTC

    Old thread, yes. But you got me thinking too. In the spirit of TMTOWTDI I offer an alternative: Put the commands in one system() call, separated by semicolons. Works for me using Perl 5.18.2 in Ubuntu 14.04 with Bash as default shell. Instead of tarring files I ran "ls -ao" after changing directories, as in the example below.

    system("cd ~/jobs; ls -ao; cd ..");
      Put the commands in one system() call, separated by semicolons.

      I see the following problems with this way:

      • Separating commands with semicolons may not work with all shells on all operating systems.
      • Using semicolons (on Unix and derivates) ignores the return values of the commands. cd may fail, too, so you may end up executing commands in the wrong directory. OOPS!
      • You mess with the shell. Shells tend to behave very different depending on operating system, shell version, shell configuration. Have a look at http://www.in-ulm.de/~mascheck/various/ for some details. You need to know the exact shell behaviour when you pass parameters to the invoked program. Do you need to quote? How to quote? How to quote quote characters inside the parameters?
      • The extra shell invoked by using the string form of system wastes resources.

      Using perl's chdir around system or between fork and exec avoids chaining commands, and using the list form of system or exec totally avoids the extra shell with all of its problems.

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
        Good points all. Agreed then, and this will come in handy in a few days for something I'm working on. Thanks for the critique.