我创建了一个脚本,该脚本将检查您提供的用户是否已登录,并在登录时显示会话的持续时间。我现在需要做的是,如果在发出命令时没有提供参数(用户名),请求一个并且具有与提供命令相同的结果。
这就是我所拥有的:
name=$(cat /etc/passwd | grep $1 | cut -d':' -f5 | tr ':' ' ' | sed 's/,//' | sed 's/^\([^ ]*\) \([^ ]*\)/\2 \1/' | sort -t' ' -k3,3)
terminal=$(who | grep $1 | cut -d' ' -f3)
loginHour=$(who | grep $1 | cut -c30-31)
loginMin=$(who | grep $1 | cut -c33-34)
loginMins=$((loginHour * 60 + loginMin))
nowHour=$(date +%R | cut -c1-2)
nowMin=$(date +%R | cut -c4-5)
nowMins=$((nowHour * 60 + nowMin))
totalMins=$((nowMins - loginMins))
hoursOn=$((totalMins / 60))
minsOn=$((totalMins % 60))
clear
echo
if [[ $# -eq 1 ]] ; then
grep -q $1 /etc/passwd
if grep -q $1 /etc/passwd ; then
clear
echo
if who | grep $1 > /dev/null ; then
echo "$name" is currently logged on to terminal "$terminal" and has been for "$hoursOn" hour"(s)" and "$minsOn" minute"(s)".
echo
exit 0
else
echo "$name" is NOT currently logged on.
echo
exit 1
fi
else
echo The user you entered is not a valid user on this system.
echo
exit 2
fi
fi
我曾尝试过,但不是理想的结果,所以我把它从混乱中删除了。
答案 0 :(得分:1)
if [[ $# -eq 0 ]]
then
read -p "Enter Name: " username
else
username=$1
fi
然后将$1
$username
答案 1 :(得分:0)
如果没有给出名字,你也可以中止
# : does nothing it just forces the evaluation
: ${1:?"Need to provide name to script"}