(Ubuntu bash 脚本)从配置文件设置权限
(Ubuntu bash script) Setting rights from a config txt
我是初学者,正在尝试编写一个脚本,该脚本采用配置文件(下面的示例)并为用户设置权限,如果该用户或组不存在,则会添加他们。
对于文件中的每一行,我将删除用户或组并检查它们是否存在。
现在我只检查用户。
#!/bin/bash
function SetRights()
{
if [[ $# -eq 1 && -f ]]
then
for line in
do
var1=$(cut -d: -f2 $line)
var2=$(cat /etc/passwd | grep $var1 | wc -l)
if [[ $var2 -eq 0 ]]
then
sudo useradd $var1
else
setfacl -m $line
fi
done
else
echo Enter the correct path of the configuration file.
fi
}
SetRights
配置文件如下所示:
u:TestUser:- /home/temp
g:TestGroup:rw /home/temp/testFolder
u:TestUser2:r /home/temp/1234.txt
输出:
grep: TestGroup: No such file or directory
grep: TestUser: No such file or directory
"The useradd help menu"
如果您能提示我在研究中应该寻找什么,我将不胜感激。
是否可以重置 var1 和 var2?使用 unset 对我不起作用,我找不到只能设置一次的变量。
不清楚您是如何遍历文件内容的 - 如果 </code> 包含文件名,您应该看不到您报告的错误。</p>
<p>但无论如何,这是一个重构版本,希望能避免您的问题。</p>
<pre><code># Avoid Bash-only syntax for function definition
SetRights() {
# Indent function body
# Properly quote ""
if [[ $# -eq 1 && -f "" ]]
then
# Read lines in file
while read -r acl file
do
# Parse out user
user=${acl#*:}
user=${user%:*}
# Avoid useless use of cat
# Anchor regex correctly
if ! grep -q "^$user:" /etc/passwd
then
# Quote user
sudo useradd "$user"
else
setfacl -m "$acl" "$file"
fi
done <""
else
# Error message to stderr
echo Enter the correct path of the configuration file. >&2
# Signal failure to the caller
return 1
fi
}
# Properly quote argument
SetRights ""
我是初学者,正在尝试编写一个脚本,该脚本采用配置文件(下面的示例)并为用户设置权限,如果该用户或组不存在,则会添加他们。
对于文件中的每一行,我将删除用户或组并检查它们是否存在。
现在我只检查用户。
#!/bin/bash
function SetRights()
{
if [[ $# -eq 1 && -f ]]
then
for line in
do
var1=$(cut -d: -f2 $line)
var2=$(cat /etc/passwd | grep $var1 | wc -l)
if [[ $var2 -eq 0 ]]
then
sudo useradd $var1
else
setfacl -m $line
fi
done
else
echo Enter the correct path of the configuration file.
fi
}
SetRights
配置文件如下所示:
u:TestUser:- /home/temp
g:TestGroup:rw /home/temp/testFolder
u:TestUser2:r /home/temp/1234.txt
输出:
grep: TestGroup: No such file or directory
grep: TestUser: No such file or directory
"The useradd help menu"
如果您能提示我在研究中应该寻找什么,我将不胜感激。
是否可以重置 var1 和 var2?使用 unset 对我不起作用,我找不到只能设置一次的变量。
不清楚您是如何遍历文件内容的 - 如果 </code> 包含文件名,您应该看不到您报告的错误。</p>
<p>但无论如何,这是一个重构版本,希望能避免您的问题。</p>
<pre><code># Avoid Bash-only syntax for function definition
SetRights() {
# Indent function body
# Properly quote ""
if [[ $# -eq 1 && -f "" ]]
then
# Read lines in file
while read -r acl file
do
# Parse out user
user=${acl#*:}
user=${user%:*}
# Avoid useless use of cat
# Anchor regex correctly
if ! grep -q "^$user:" /etc/passwd
then
# Quote user
sudo useradd "$user"
else
setfacl -m "$acl" "$file"
fi
done <""
else
# Error message to stderr
echo Enter the correct path of the configuration file. >&2
# Signal failure to the caller
return 1
fi
}
# Properly quote argument
SetRights ""