gpt4 book ai didi

bash - 如何创建 100 个文件,每个文件中有 1 个随机数,并根据数字授予它们权限

转载 作者:行者123 更新时间:2023-12-01 23:08:27 24 4
gpt4 key购买 nike

我需要创建一个 bash 脚本来创建 100 个文件,其中包含随机数。我尝试使用:

for i in {1..100}; do $RANDOM > RANDOM.txt

我不知道这样做是否正确。然后我需要根据文件中的数字给文件读写和执行权限。不知道该怎么做。我尝试使用:

if [ $i%2==0 ]
then
echo chmod +rw $RANDOM.txt

但这似乎行不通

刚收到一些反馈,结果证明我做错了一切。我必须创建 100 个文件 1.txt 到 100.txt 我使用 touch {1..100}.txt 然后在每个文件中粘贴 1 个随机数。我应该使用 echo 还是 shuf 来执行此操作?

最佳答案

我认为使用 chmod 最简单具有八进制权限,例如 0777对于 rwxrwxrwx

例子:

#!/bin/bash

for((i=0; i<100; ++i)) {
rnd=$RANDOM # pick a random number
(( perm = rnd % 512 )) # make it in the range [0, 512) (0000-0777 oct)
printf -v octperm "%04o" $perm # convert to octal

file=$rnd.txt # not sure if you meant to name it after the number
echo $rnd > $file

chmod $octperm $file # chmod with octal number
}

文件摘录:

-r-xrw--wx 1 ted users   5 15 dec 17.53 6515.txt
---x-wxrwx 1 ted users 5 15 dec 17.53 6751.txt
-rwx-w--w- 1 ted users 5 15 dec 17.53 8146.txt
-rw-r----- 1 ted users 5 15 dec 17.53 8608.txt
--w--w---x 1 ted users 5 15 dec 17.53 8849.txt
--wx----wx 1 ted users 5 15 dec 17.53 8899.txt
--wxrwx-wx 1 ted users 5 15 dec 17.53 8955.txt
-rw-r-xrw- 1 ted users 5 15 dec 17.53 9134.txt
...

如果您想使用当前的 umask考虑到,您也可以这样做,方法是屏蔽掉 umask 指示的权限中的位。 .

#!/bin/bash

(( um = ~$(umask) )) # bitwise negated umask

for((i=0; i<100; ++i)) {
rnd=$RANDOM

(( perm = (rnd % 01000) & um )) # [0000,0777] bitwise AND umask
printf -v octperm "%04o" $perm

file=$i.$rnd.txt # using $i. to make name unique
echo $rnd > $file

chmod $octperm $file
}

如果您的 umask目前是0022上面的示例不会为 group 和/或 others 创建任何可写的文件,而其他(正常)权限将是随机的。

关于bash - 如何创建 100 个文件,每个文件中有 1 个随机数,并根据数字授予它们权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70367320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com