OH, sorry for my poor English.
Infact what I want to do is not "use ruby like shell script" but "use shell
in ruby".
For instant, I wonder if I can use "ls | grep" or "tar -xvf | grep" to get a
file list and store it in a ruby array, and handle them with io#gets.
I don't know what "back ticks" are.
Thank for all the replies.
`backticks` are the keyboard symbol below the tilde.
backticks in a shell are the closest thing to object like programming
in the shell. The concept is part of what is known as shell
substitution and shell expansion.
The idea is that anything within the backticks are ran in a new shell
which inherits the environment and user created variables to the new
'sub' shell. of course the sub shell can spawn it's own shells and so
on.
In shell scripting the interpolation is done via ${ } which works the
same way as ruby's #{ }. This as well as the backticks follow the ruby
principle of least surprise( at least for shell coders).
If your looking for portability from unix to windows the Dir command
looks to be the best bet. Dir.glob("*") will return an array ready to
be parsed.
`ls` will return a string. you will need to parse it yourself or
create your own to_array via storing strings delimited on '/n'
If your just interested in programming for system automation on
unix/linux systems note that the commands from the gnu set may be a
bit different from *bsd and some commercial unixes. To keep everything
portable consider programming based on posix standards as to run on
every system with only ruby being the dependency.
if you need to capture stderr you can add 2>&1 inside the backticks.
Here is an example irb session:
ruby-1.9.2-head > sysout = `echo foo | sed s/foo/bar/g`
=> "bar\n"
ruby-1.9.2-head > $?
=> #<Process::Status: pid 5029 exit 0>
ruby-1.9.2-head > sysout = `echo foo | sed s/foo/bar/g 2>&1`
=> "bar\n"
ruby-1.9.2-head > $?
=> #<Process::Status: pid 5032 exit 0>
ruby-1.9.2-head > sysout = `echo foo | gsed s/foo/bar/g 2>&1`
=> "sh: gsed: command not found\n"
ruby-1.9.2-head > $?
=> #<Process::Status: pid 5035 exit 127>
ruby-1.9.2-head > sysout = `echo foo | gsed s/foo/bar/g`
sh: gsed: command not found
=> ""
ruby-1.9.2-head > $?
=> #<Process::Status: pid 5038 exit 127>
hope this helps
happy hacking!