【发布时间】:2018-05-18 05:53:28
【问题描述】:
我正在尝试使用 watch 查看 shell 脚本的输出,执行 /bin/bash 并将脚本本身保存在 heredoc 中。
鼻屎只执行一次。它给出了正确的输出,然后观察刷新并且屏幕变为空白。退出 watch 后没有列出任何错误。
我不知道问题出在哪里,因为使用 watch 调试变得越来越困难 > bash > heredoc > ugly code。
好消息是heredoc 中的ugly code 工作正常。
function show_users {
[[ -z $1 ]] && watchtime=1 || watchtime=$1
[[ -z $2 ]] && export userToShow="mydefaultuser" || export userToShow=$2
echo "Setting up watch for user ${userToShow}"
watch -n $watchtime --no-title /bin/bash <<-'EOF'
#Show finger results of requested user
finger ${userToShow}
#show list of users su'd into requested user
echo "************************************************************************************"
echo "users logged in as ${userToShow}"
#get the parent PIDS of any process belonging to requested user
#into a list that can be read by grep
parentPIDs=$(ps -ef | grep "su - ${userToShow}" | grep -v 'grep\|finger' | awk 'NR>1{printf " %s \\|",parentpid}{parentpid=$3}END{printf " %s\n", parentpid}')
#get usersnames associated to those parent PIDS
parentUsers=$(ps -ef | grep "${parentPIDs}" | grep -v "grep\|${userToShow}" | awk '{print $1}' | sort | uniq)
#finger each of these users and get their full name
while IFS= read -r line ; do
printf "%s: " $line
parentName=$(finger $line | awk -F":" 'NR==1{print $3}')
echo $parentName
done <<< "${parentUsers}"
#show tree for all proceses being run by requested user up to root.
echo "************************************************************************************"
ps -ef --forest | egrep -e "sshd:|-ksh|$userToShow" | grep -v grep | awk 'root==1{print ""} NR>1{print line} {line=$0;root=($1=="root") ? 1 : 0}'
EOF
}
像这样称呼:
show_users 2 "username"
【问题讨论】:
-
基本问题是heredoc附加到只执行一次的watch的stdin。第一个
bash继承stdin 并消耗所有here doc,当调用下一个bash 时,stdin 中没有任何内容。 (只是评论,因为我没有好的解决方案。) -
@CharlesBailey 我在想这样的事情就是这样。也许如果我将
catheredoc 变成一个变量,然后将bash -c变量放在watch... 我会继续修修补补。 -
MCVE 中的 M 是“最小”。你可以用
watch /bin/bash << 'EOF'dateEOF替换整篇文章 -
定义一个函数并
export -f它。然后你可以简单地watch bash -c yourfunc -
ps解析是一种常见且广泛使用的反模式。如果您仍然在运行 Awk,您也可以轻松地将grep分解到 Awk 脚本中。见useless use ofgrep.