我正在尝试基于变量test_1.txt
中可用的值来更新作为主文件test.txt
内部内容的IN
的文件许可权。下面的脚本将帮助根据我的要求修改内容。但是我需要减少代码行数。因此,您可以提出任何减少行数并实现相同输出的方法的建议。
代码
#!/bin/bash
IN=750
Input=test.txt
Char_one=$(echo $IN | cut -c 1)
Char_two=$(echo $IN | cut -c 2)
Char_three=$(echo $IN | cut -c 3)
if [[ "$Char_one" == "7" ]]; then
Char_one="rwx"
elif [[ "$Char_one" == "6" ]]; then
Char_one="rw-"
elif [[ "$Char_one" == "5" ]]; then
Char_one="r-x"
elif [[ "$Char_one" == "4" ]]; then
Char_one="r--"
elif [[ "$Char_one" == "3" ]]; then
Char_one="-wx"
elif [[ "$Char_one" == "2" ]]; then
Char_one="rwx"
elif [[ "$Char_one" == "1" ]]; then
Char_one="-w-"
elif [[ "$Char_one" == "0" ]]; then
Char_one="---"
fi
if [[ "$Char_two" == "7" ]]; then
Char_two="rwx"
elif [[ "$Char_two" == "6" ]]; then
Char_two="rw-"
elif [[ "$Char_two" == "5" ]]; then
Char_two="r-x"
elif [[ "$Char_two" == "4" ]]; then
Char_two="r--"
elif [[ "$Char_two" == "3" ]]; then
Char_two="-wx"
elif [[ "$Char_two" == "2" ]]; then
Char_two="rwx"
elif [[ "$Char_two" == "1" ]]; then
Char_two="-w-"
elif [[ "$Char_two" == "0" ]]; then
Char_two="---"
fi
if [[ "$Char_three" == "7" ]]; then
Char_three="rwx"
elif [[ "$Char_three" == "6" ]]; then
Char_three="rw-"
elif [[ "$Char_three" == "5" ]]; then
Char_three="r-x"
elif [[ "$Char_three" == "4" ]]; then
Char_three="r--"
elif [[ "$Char_three" == "3" ]]; then
Char_three="-wx"
elif [[ "$Char_three" == "2" ]]; then
Char_three="rwx"
elif [[ "$Char_three" == "1" ]]; then
Char_three="-w-"
elif [[ "$Char_three" == "0" ]]; then
Char_three="---"
fi
while IFS= read -r line;
do
j=1
perm_1=$(echo $line | awk '{print $1}' | cut -c 2-4)
perm_2=$(echo $line | awk '{print $1}' | cut -c 5-7)
perm_3=$(echo $line | awk '{print $1}' | cut -c 8-10)
Def_Chmod=$(echo "$line" | sed -i "$j s/$perm_1$perm_2$perm_3/$Char_one$Char_two$Char_three/;" "$Input")
j=$((j+1))
done <"$Input"
test.txt
-rwxrwxr-x test_1.txt
输出
执行上述代码后test.txt
文件的内容。
-rwxr-x--- test_1.txt
请您尝试以下操作:
IN=750
Input=test.txt
str="-rwxrwxrwx" # start with the full permissions
for (( i=0; i<${#str}; i++ )); do # loop from LSB to MSB
j=$(( 1<<i )) # j changes as 1, 2, 4, 8 ...
if (( ( 8#$IN & j ) == 0 )); then # the bit is "off"
str=${str:0:9-i}"-"${str:10-i:i}
# then replace the position with "-"
fi
done
# echo "$str" # just for debugging
sed -i "s/^[-rwx]\{10\}/$str/" "$Input" # update the permission string
然后test.txt
将被修改为:
-rwxr-x--- test_1.txt
str
。IN
。IN
的位片为0
,则将相关标志替换为破折号-
。Input
。请注意,您无需创建while
循环即可读取逐行输入文件。 Sed
将为您进行迭代。