exec the cd command in a ruby script

前端 未结 6 384
情深已故
情深已故 2021-01-13 21:52

I\'d like to change the pwd of the current shell from within a ruby script. So:

> pwd
/tmp
> ruby cdscript.rb
> pwd
/usr/bin

This

相关标签:
6条回答
  • 2021-01-13 22:34

    You won't be able to change the working directory of your shell.

    When it executes ruby, it forks so you get a new environment, with a new working directory.

    0 讨论(0)
  • 2021-01-13 22:36

    As other answers already pointed out, you can change the pwd inside your ruby script, but it only affects the child process (your ruby script). A parent process' pwd cannot be changed from a child process.

    One workaround could be, to have the script output the shell command(s) to execute and call it in backticks (i.e. the shell executes the script and takes its output as commands to execute)

    myscript.rb:

    # … fancy code to build somepath …
    puts "cd #{somepath}"
    

    to call it:

    `ruby myscript.rb`
    

    make it a simple command by using an alias:

    alias myscript='`ruby /path/to/myscript.rb`'
    

    Unfortunately, this way you can't have your script output text to the user since any text the script outputs is executed by the shell (though there are more workarounds to this as well).

    0 讨论(0)
  • 2021-01-13 22:38

    You can't change the working directory (or the environment variables for that matter) of the shell that invoked you in a ruby script (or any other kind of application). The only commands that can change the pwd of the current shell are shell built-ins.

    0 讨论(0)
  • 2021-01-13 22:41

    You can try to use system instead of exec. It works for me.

    Like system("cd #{new_path} && <statement> && cd #{original_path}")

    0 讨论(0)
  • 2021-01-13 22:42

    Stumbled across this while searching to do the same thing.

    I was able to solve this by running multiple statements within the backticks.

    'cd #{path} && <statement> && cd ..'
    
    0 讨论(0)
  • 2021-01-13 22:53

    Dir.chdir("/usr/bin") will change the pwd within the ruby script, but that won't change the shell's PWD as the script is executed in a child process.

    0 讨论(0)
提交回复
热议问题