Split the string to get only the first 5 characters

风格不统一 提交于 2019-12-03 00:45:40

问题


I would like to go to the location /var/log/src/ap-kernelmodule-10.001-100

But looks like my code has to deal with ap-kernelmodule-10.002-100, ap-kernelmodule-10.003-101 etc. I would like to reach the location with a split string and execute my command. eg : /var/log/src/ap-kernelmodule-10./

This ruby script for a Linux machine, so I used Mixlib:: ShellOut.

begin  
cmd = Mixlib::ShellOut.new("command run here" , :cwd => 
'/var/cache/acpchef/src/ap-kernelmodule-10xxx')
 cmd.run_command
end

回答1:


You can't be in multiple cwds simultaneously. To run the command for each directory that matches the pattern, you can use Dir#glob:

Dir.glob('/var/cache/acpchef/src/ap-kernelmodule-10*').each do |cwd|
  Mixlib::ShellOut.new("command run here", cwd: cwd).run_command
end



回答2:


I am not quite get on what you really want to achieve. Question is rather ambiguous.

You know you would like to go to /var/log/src/ap-kernelmodule-10.001-100 and run a command, the most obvious way is you could just use:

execute "command run here" do
 cwd "/var/log/src/ap-kernelmodule-10.001-100"
end

But if you would like to run a command for each directory like you said in ap-kernelmodule-10.002-100, ap-kernelmodule-10.003-101 etc. with /var/log/src/ap-kernelmodule-10.*/ sequentially.

Then you could do with:

Dir.glob("/var/log/src/ap-kernelmodule-10.*").each do |folder|
  execute "command run here" do
   cwd folder
  end
end

Additionally, parallel resources execution is not possible natively in chef (AFAIK). So, the possible workaround is to use bash or ruby_block resource to construct commands to be executed in xargs, parallel or similar tools.

Hope this helps.



来源:https://stackoverflow.com/questions/52812166/split-the-string-to-get-only-the-first-5-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!