简体   繁体   English

使用Ruby和命令行工具在ubuntu中更改目录

[英]Changing directory in ubuntu with Ruby and a command line tool

#!/home/user/.rvm/rubies/ruby-2.0.0-p353/bin/ruby

 case ARGV[0]
        when "apache"
                exec('cd /etc/apach2')
                exec('sudo nano httpd.conf')

        #...
 end

I am trying to make a quick command line tool that will change directories for me with one word.. so from the command line (in ubuntu 12). 我正在尝试制作一个快速的命令行工具,它将用一个单词为我更改目录..因此可以从命令行(在ubuntu 12中)进行。 It tells me it cant cd.. But I try the command myself and it will work just fine. 它告诉我不能cd。但是我自己尝试该命令,它将正常工作。

Ruby's Dir class is your friend for this, check-out the chdir method: Ruby的Dir类是您的朋友,请查看chdir方法:

Dir.chdir('/path/to/change/to')

will change Ruby's concept of the current working directory for the time the code is running. 在代码运行时,它将更改Ruby对当前工作目录的概念。 Any sub-shells would consider that their starting directory. 任何子Shell都会将其视为起始目录。

You can also pass chdir a block, and all code in that block will assume the new directory, which will then revert to the old one when the block exits: 您还可以向chdir传递一个块,该块中的所有代码将采用新目录,然后在该块退出时将其还原为旧目录:

Dir.chdir('/path/to/change/to') do
  # do some stuff
end

OK, so I did this and it works (I'm on OS X but should be the same): 好的,所以我做到了并且可以正常工作(我在OS X上,但应该相同):

ARGV[0]
  when "testme"
    system('cd ripple')
    system('ls -al')

    #...
end

calling system('cd ... does not change move you to that directory in the current shell you are executing your .rb file in. So it would make more sense to do: 调用system('cd ...不会更改,将您移动到正在执行.rb文件的当前shell中的该目录。因此这样做更有意义:

system('sudo nano /etc/....

all on one line 全线

I tested it with back ticks and it didn't work at all for me. 我用背tick进行了测试,但对我来说根本不起作用。

I tested with exec() and got the expected result, it runs one line and that's it. 我使用exec()进行了测试,并得到了预期的结果,它只运行一行,仅此而已。 So exec() could work if you only have one command to run or you chain them all together with && 因此,如果只有一个命令要运行,或者使用&&它们全部链接在一起,则exec()可以工作

exec('ls /etc && sudo nano /etc/....

I would read this: http://rubyquicktips.com/post/5862861056/execute-shell-commands 我会读这个: http : //rubyquicktips.com/post/5862861056/execute-shell-commands

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM