exec the cd command in a ruby script

前端 未结 6 419
情深已故
情深已故 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: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).

提交回复
热议问题