我试图让这个脚本工作,但我得到的是:
14:语法错误:“(”意外(期望“fi”)。
希望你们能解决我的问题,因为我调查错误已经有一段时间了...如果您需要该.csv文件,请告诉我。
这是脚本:
#!/bin/bash
filein="proyecto3.csv"
IFS=$'\n'
if [ ! -f "$filein" ]
then
echo "Cannot find file $filein"
else
groups=(`cut -d: -f 6 "$filein" | sed 's/ //'`)
fullnames=(`cut -d: -f 1 "$filein"`)
userid=(`cut -d: -f 2 "$filein"`)
usernames=(`cut -d: -f 1 "$filein" | tr [A-Z] [a-z] | awk '{print substr($1,1,1) $2}'`)
fi
for group in ${groups[*]}
do
grep -q "^$group" /etc/group ; let x=$?
if [ $x -eq 1 ]
then
groupadd "$group"
fi
done
x=0
created=0
for user in ${usernames[*]}
do
useradd -n -c ${fullnames[$x]} -g "${groups[$x]}" $user 2> /dev/null
if [ $? -eq 0 ]
then
let created=$created+1
fi
echo "${usernames[$x]}" | passwd --stdin "$user" > /dev/null
echo "Complete. $created accounts have been created."
fi
Run Code Online (Sandbox Code Playgroud)
只需删除脚本中的最后一行(这也有助于进行适当的缩进以查看错误)。你也忘了用 done 结束你的最后一个 for 循环:
#!/bin/bash
filein="proyecto3.csv"
IFS=$'\n'
if [ ! -f "$filein" ]
then
echo "Cannot find file $filein"
else
groups=(`cut -d: -f 6 "$filein" | sed 's/ //'`)
fullnames=(`cut -d: -f 1 "$filein"`)
userid=(`cut -d: -f 2 "$filein"`)
usernames=(`cut -d: -f 1 "$filein" | tr [A-Z] [a-z] | awk '{print substr($1,1,1) $2}'`)
fi
for group in ${groups[*]}
do
grep -q "^$group" /etc/group ; let x=$?
if [ $x -eq 1 ]
then
groupadd "$group"
fi
done
x=0 #not sure why you reset x here to zero !?
created=0
for user in ${usernames[*]}
do
useradd -n -c ${fullnames[$x]} -g "${groups[$x]}" $user 2> /dev/null
if [ $? -eq 0 ]
then
let created=$created+1
fi
done
echo "${usernames[$x]}" | passwd --stdin "$user" > /dev/null
echo "Complete. $created accounts have been created."
Run Code Online (Sandbox Code Playgroud)
到目前为止,我真的建议您shellcheck在脚本中使用类似的东西(您可以从普通的 Ubuntu Universe 存储库中获取它)。
sudo apt update
sudo apt install shellcheck
Run Code Online (Sandbox Code Playgroud)
它会输出更多您可以在脚本上做得更好的内容:
$ shellcheck test.sh
In test.sh line 9:
groups=(`cut -d: -f 6 "$filein" | sed 's/ //'`)
^-- SC2006: Use $(..) instead of legacy `..`.
In test.sh line 10:
fullnames=(`cut -d: -f 1 "$filein"`)
^-- SC2006: Use $(..) instead of legacy `..`.
In test.sh line 11:
userid=(`cut -d: -f 2 "$filein"`)
^-- SC2034: userid appears unused. Verify it or export it.
^-- SC2006: Use $(..) instead of legacy `..`.
In test.sh line 12:
usernames=(`cut -d: -f 1 "$filein" | tr [A-Z] [a-z] | awk '{print substr($1,1,1) $2}'`)
^-- SC2006: Use $(..) instead of legacy `..`.
^-- SC2060: Quote parameters to tr to prevent glob expansion.
^-- SC2060: Quote parameters to tr to prevent glob expansion.
In test.sh line 29:
useradd -n -c ${fullnames[$x]} -g "${groups[$x]}" $user 2> /dev/null
^-- SC2086: Double quote to prevent globbing and word splitting.
^-- SC2086: Double quote to prevent globbing and word splitting.
In test.sh line 30:
if [ $? -eq 0 ]
^-- SC2181: Check exit code directly with e.g. 'if mycmd;', not indirectly with $?.
Run Code Online (Sandbox Code Playgroud)
或者,使用在线 shellcheck工具...