2

In Linux, it is very easy "just" to add executable to a file, simply by input:

chmod +x <fname>

However, I have failed to find something as easy in the gems of Ruby. Of course, one could do a system call, i.e.

system( 'chmod +x' << fname )

However, I am looking for something more 'elegant'.

I'm using Ruby 1.8.7.

Martin Tournoij
  • 23,567
  • 24
  • 90
  • 127
user1134991
  • 2,723
  • 2
  • 16
  • 25
  • 1
    Perhaps this would be useful: http://ruby-doc.org/stdlib-2.2.2/libdoc/fileutils/rdoc/FileUtils.html#method-c-chmod – Lix Mar 07 '16 at 14:41
  • Indeed it does. Unfortunately, I was having a search options to the Ruby 1.8.7, which does not have it... Well, 2 issues resolved for the price on 1... – user1134991 Mar 07 '16 at 14:54
  • Oh - I see... It might be a good idea to include the ruby version you are working with (especially if it is one of your limitations) – Lix Mar 07 '16 at 15:42
  • From [Ruby 1.8.7 documentation](http://ruby-doc.org/stdlib-1.8.7/libdoc/fileutils/rdoc/FileUtils.html#method-c-chmod): `FileUtils.chmod 0644, '/my/directory/which/contains/my/file'`. –  Mar 07 '16 at 16:34
  • Yeah, but how do I know the "other permissions", that is, I do not want to change write/read permissions. I could read them in, and bitwise them, I guess... – user1134991 Mar 07 '16 at 17:12
  • The "symbolic mode" syntax (`+x` etc.) is a feature of the `chmod(1)` utility. AFAIK no programming language supports that. You'll need to write a wrapper around `FileUtils.chmod`, or (better) just use octal permissions ;-) – Martin Tournoij Mar 07 '16 at 17:36

2 Answers2

12
require "fileutils"

FileUtils.chmod("+x", "foo.sh")
deivid
  • 3,888
  • 1
  • 26
  • 36
2

You can read the current mode using File.stat and then bitwise '''or''' it with a mask to achieve what you want. Here is a sample (which could be shortened):

current_mask = File.stat('foo.sh').mode new_mask = current_mask | '0000000000000001'.to_i(2) File.chmod(new_mask, 'foo.sh')

Pascal
  • 7,454
  • 1
  • 18
  • 27