我想改变一个数组的值,并希望得到任何帮助.
我有一个像这样的数组:
users=(root isometric akau)
Run Code Online (Sandbox Code Playgroud)
(这实际上是当前用户的列表)我希望能够测试用户是否存在以及他们是否存在,然后从数组中删除该人.我已经尝试过将它放在for循环中并进行评估:
for i in ${users[@]}; do
eval "users=($([ -z $(grep \"^\$i\" /etc/shadow) ] && sed \"s/\$i//g\"))"
done
echo $users
Run Code Online (Sandbox Code Playgroud)
我想再玩这个,但我想我可能会变得太复杂(我不确定我可以把命令放在一个数组中).任何人都知道如何做到这一点?
编辑:
我如何输入数组变量未设置数:
cnt=0
for i in ${users[@]}; do
[ -z "$(grep "^$i" /etc/shadow)" ] && unset users[cnt] || ((cnt++))
done
Run Code Online (Sandbox Code Playgroud)
EDIT2:
实际上丹尼斯的表现更好.
你可能不需要for循环.试试这个:
users=(root isometric akau)
list="${users[@]/%/|}" # convert array to list, add pipe char after each user
# strip the spaces from the list and look for usernames between the beg. of the line
# and the end of the word, make an array out of the result
users=($(grep -Eo "^(${list// })\>" /etc/shadow))
Run Code Online (Sandbox Code Playgroud)
的grep,解开,应该是这样的:
grep -Eo "^(root|isometric|akau|)\>" /etc/shadow
Run Code Online (Sandbox Code Playgroud)