”-rwxrwxrwx”形式のパーミッション文字列を8進数の値に変換する関数
"-rwxrwxrwx"形式のパーミッション文字列を8進数の値に変換する関数を書きました。
# "-rwxrwxrwx"形式の文字列を8進数の値に変換する。 def to_oct( permition ) raise "illegal format" unless permition =~ /[\-dbclps]([\-r])([\-w])([\-sxS])([\-r])([\-w])([\-sxS])([\-r])([\-w])([\-xtT])/ i = 0 i |= 4 << 6 if $1 == "r" i |= 2 << 6 if $2 == "w" i |= 1 << 6 if $3 == "x" || $3 == "s" i |= 4 << 9 if $3 == "s" || $3 == "S" i |= 4 << 3 if $4 == "r" i |= 2 << 3 if $5 == "w" i |= 1 << 3 if $6 == "x" || $6 == "s" i |= 2 << 9 if $6 == "s" || $6 == "S" i |= 4 if $7 == "r" i |= 2 if $8 == "w" i |= 1 if $9 == "x" || $9 == "t" i |= 1 << 9 if $9 == "t" || $9 == "T" return "%04o" % i end puts to_oct( "-r--r--r--" ) puts to_oct( "-rwxrwxrwx" ) puts to_oct( "dr-xrw--wx" ) puts to_oct( "-r-srwSrwt" ) puts to_oct( "---Srwsr-T" )
実行結果です。
0444 0777 0563 7567 7074
もうちょいスマートに書けんもんかな。