我正在编写一个脚本,在其中将本地用户放入数组中,并在for循环中使用它们,同时使用set进行解析以显示最后的命令信息。如果仅在脚本中运行,我就能成功解析“ do”部分中的命令。
#!/bin/bash
#Automation Project (Khal)
#Author: Zacquille Joseph
#Version 1.2
#Get Users on System
user=$(getent passwd {1000..60000} | cut -d: -f1 )
#Puts all Users into Array
array=($user)
for item in ${array[*]}
do
set $(last | grep -w $item | head -n 1 )
echo
echo $*
echo "Name: $1"
echo "Date: $4 $5 $6"
echo "Time: $7"
echo "Status: $7 $8 $9 ${10}"
echo
done
我希望只有
的输出mary pts/2 X.X.X.X Wed Apr 17 15:31 - 15:36 (00:04)
Name: mary
Date: Wed Apr 17
Time: 15:31
Status: 15:31 - 15:36 (00:04)
zac pts/0 X.X.X.X Tue Apr 30 14:10 still logged in
Name: zac
Date: Tue Apr 30
Time: 14:10
Status: 14:10 still logged in
相反,我将其与此结合起来:
BASH=/bin/bash
BASHOPTS=cmdhist:complete_fullquote:extquote:force_fignore:hostcomplete:interactive_comments:progcomp:promptvars:sourcepath
BASH_ALIASES=()
BASH_ARGC=()
BASH_ARGV=()
BASH_CMDS=()
BASH_LINENO=([0]="0")
BASH_SOURCE=([0]="./cst1.sh")
BASH_VERSINFO=([0]="4" [1]="4" [2]="19" [3]="1" [4]="release" [5]="x86_64-pc-linux-gnu")
BASH_VERSION='4.4.19(1)-release'
DIRSTACK=()
EUID=1004
GROUPS=()
.....
仅供参考:
last | grep -w zac | head -n 1
将返回此:
zac pts/0 X.X.X.X Tue Apr 30 14:10 still logged in
运行此:
set $(last | head -n 10 | tail -n 1)
echo
echo $*
echo "Name: $1"
echo "Date: $4 $5 $6"
echo "Time: $7"
echo "Status: $7 $8 $9 ${10}"
echo
将返回:
ubuntu pts/4 X.X.X.X Thu Apr 18 22:47 - 01:01 (02:13)
Name: ubuntu
Date: Thu Apr 18
Time: 22:47
Status: 22:47 - 01:01 (02:13)
答案 0 :(得分:1)
尝试使用另一个数组代替set命令,例如:
arr2=($(last | grep -w $item | head -n 1 ))
echo
echo $*
echo "Name: ${arr2[0]} "
echo "Date: ${arr2[3]} ${arr2[4]} ${arr2[5]} "
echo "Time: ${arr2[6]}"
echo "Status: ${arr2[6]} ${arr2[7]} ${arr2[8]} ${arr2[9]}"
echo
答案 1 :(得分:0)
解决了!其中一个用户从未登录,但已创建。就我的脚本而言,所有用户都必须登录。理想情况下,我只是用每个用户替换$item
并运行脚本(幸运的是我们不需要太多用户),然后发现一个从未登录的特定用户给出了大输出。