如何通过字符串获取权限号:-rw-r--r--

cnd*_*cnd 64 chmod

我需要设置相同的 chmod,如何获取-rw-r--r-- 的编号

小智 79

r=4
w=2
x=1
Run Code Online (Sandbox Code Playgroud)

在每个组中。你的例子是 6(r+w=4+2)4(r=4)4(r=4)。


lik*_*lik 61

请检查stat输出:

# stat .xsession-errors 
  File: ‘.xsession-errors’
  Size: 839123          Blocks: 1648       IO Block: 4096   regular file
Device: 816h/2070d      Inode: 3539028     Links: 1
Access: (0600/-rw-------)  Uid: ( 1000/     lik)   Gid: ( 1000/     lik)
Access: 2012-05-30 23:11:48.053999289 +0300
Modify: 2012-05-31 07:53:26.912690288 +0300
Change: 2012-05-31 07:53:26.912690288 +0300
 Birth: -
Run Code Online (Sandbox Code Playgroud)

  • `stat -c %a /path/to/file` 是你需要的魔术。 (14认同)

Jan*_*der 30

完整权限模式编号是一个 4 位八进制数,但大多数情况下,您只使用 3 个最低有效位。将权限字符串中的每个组相加,取 r=4、w=2、x=1。例如:

 421421421
-rwxr-xr--
 \_/        -- r+w+x = 4+2+1 = 7
    \_/     -- r+_+x = 4+0+1 = 5
       \_/  -- r+_+_ = 4+0+0 = 4     => 0754
Run Code Online (Sandbox Code Playgroud)

现在,有时您会看到像这样的奇怪模式字符串:

-rwsr-xr-T
Run Code Online (Sandbox Code Playgroud)

第四个数字被重载到模式x字符串中的位上。如果您看到x除此之外的字母,则表示设置了这些“特殊”第四位之一,如果字母为小写,则x也设置了该位置。所以这一篇的翻译是:

   4  2  1
 421421421
-rwsr-xr-T
   +  +  +  -- s+_+T = 4+0+1 = 5  
 \_/        -- r+w+s = 4+2+1 = 7  (s is lowercase, so 1)
    \_/     -- r+_+x = 4+0+1 = 5
       \_/  -- r+_+T = 4+0+0 = 4  (T is uppercase, so 0)   => 05754
Run Code Online (Sandbox Code Playgroud)

显示数字是八进制的标准 UNIX 方法是以零开头。chmod无论如何,GNU都会假设您提供的模式是八进制,但最安全的是在前面加上零。

最后,如果您+在模式字符串的末尾看到 a :

-rwxr-xr-x+
Run Code Online (Sandbox Code Playgroud)

那么这意味着该文件具有扩展权限,您将需要超过chmod. 对于初学者,请查看setfaclgetfacl命令。


小智 12

这可能很简单

-bash-3.2$ stat --format=%a sample_file
755
Run Code Online (Sandbox Code Playgroud)


ImH*_*ere 5

权限只是二进制数的字符串表示。
0主要由代表-,其余的都是字母。

基本的

对于基本权限:

将所有-和大写S或转换T0,其余的应表示1
如此构造的结果二进制数应打印为八进制:

$ a=-rw-r--r--
$ b=${a//[ST-]/0}
$ b=${b//[!0]/1}
$ printf '%04o\n' $((2#$b))
0644
Run Code Online (Sandbox Code Playgroud)

在一行中:

$ b=${a//[ST-]/0}; b=${b//[!0]/1}; printf '%04o\n' $((2#$b))
0644
Run Code Online (Sandbox Code Playgroud)

纠错和检测其他 3 位100020004000需要更多代码:

#!/bin/bash

Say     (){ printf '%s\n' "$@"; }
SayError(){ a=$1; shift; printf '%s\n' "$@" >&2; exit "$a"; }

e1="Permission strings should have 10 characters or less"
e2="Assuming first character is the file type"
e3="Permission strings must have at least 9 characters"
e4="Permission strings could only contain 'rwxsStT-'"

a=$1

((${#a}>10))  &&   SayError 1 "$e1"
((${#a}==10)) && { Say        "$e2"; a=${a#?}; }
((${#a}<9))   &&   SayError 2 "$e3"
a=${a//[^rwxsStT-]}
((${#a}<9))   &&   SayError 3 "e4"
b=${a//[ST-]/0}; b=${b//[!0]/1}; c=0
[[ $a =~ [sS]......$ ]] && c=$((c|4)) 
[[ $a =~    [sS]...$ ]] && c=$((c|2)) 
[[ $a =~       [tT]$ ]] && c=$((c|1))

printf '%04o\n' "$((2#$b|c<<9))"
Run Code Online (Sandbox Code Playgroud)