Kenny Peng
Kenny Peng

Reputation: 1931

Replicating chmod's symbolic mode in Ruby without explicitly invoking a system command

On Unix/Linux systems, the chmod function supports "symbolic modes", meaning you can do what is essentially bit-arithmetic with permissions, e.g. chmod u+x ... is a symbolic form for adding executable permissions for the user. The chmod function in Ruby's FileUtils only supports an absolute bitmask as a permission, i.e. you can only do FileUtils.chmod(0777, ...) but FileUtils.chmod('u+x', ...) will not work.

I get that one way to do this is to just call the system command directly: system("chmod u+x ..."), but I'd prefer to keep code in the Ruby domain as much as possible without spawning shells everywhere. Alternatively, I could iterate through File objects, File.stat them, get their existing bitmasks and modify them individually, but symbolic modes will support a file glob, which is much more succinct and less error prone.

Does anyone know whether there is a way to do this in a more elegant way?

Upvotes: 3

Views: 501

Answers (1)

Michael Kohl
Michael Kohl

Reputation: 66867

What version of Ruby are you using? Look at the 1.9.3 docs for FileUtils.chmod:

Changes permission bits on the named files (in list) to the bit pattern represented by mode. mode is the symbolic and absolute mode can be used. Absolute mode is

FileUtils.chmod 0755, 'somecommand'
FileUtils.chmod 0644, %w(my.rb your.rb his.rb her.rb)
FileUtils.chmod 0755, '/usr/bin/ruby', :verbose => true

Symbolic mode is

FileUtils.chmod "u=wrx,go=rx", 'somecommand'
FileUtils.chmod "u=wr,go=rr", %w(my.rb your.rb his.rb her.rb)
FileUtils.chmod "u=wrx,go=rx", '/usr/bin/ruby', :verbose => true

Upvotes: 2

Related Questions