【问题标题】:Bash Scripting (Linux) [closed]Bash 脚本(Linux)[关闭]
【发布时间】:2017-05-02 15:23:01
【问题描述】:

我必须用一条小消息问候我的用户: 问候语应根据一天中的时间显示“早上好、下午好和晚上好”。

我的代码(与时间相关)没有完全工作,因为它总是显示“晚上好”,我没有发现任何明显的错误吗?

echo "please enter a username:" 
read username

username=$(getent passwd "$USER" |cut -d ':' -f 5 | ',' -f 1)
echo "Welcome $username" | cat >> output.txt

current_data_time = "'date +%Y%m%d%H%M%S'";
echo $current_data_time;

TIME=$(date +H")
hours= date +"%H | sed -e 's/^0/g'

if [ $TIME -lt 12 ]; then
echo "Good morning $username"
elif [ $TIME -lt 18 ]]; then
echo "Good afternoon $username"
else
echo "Good evening $username"
fi

【问题讨论】:

  • 试试getent passwd "$USER" ...
  • 尝试先运行脚本,看看你得到的错误,然后修复它们。有几个地方的脚本包含您在脚本其他地方使用过的内容的明显拼写错误。
  • 请参阅minimal reproducible exampleHow do I ask a good question?。 StackOverflow 问题应该专注于单个特定问题,并删除与该问题无关的任何内容。在这里,您有一大堆与问题无关的代码,并且根本没有描述问题中出现的问题。
  • 顺便说一句,这个练习来自哪里?
  • 在此处询问代码之前,您也可以先解决shellcheck.net 可以找到的任何问题。

标签: linux bash


【解决方案1】:

只是为了好玩......

hope=(morning{,} afternoon evening)
printf -v hrclass "%(%H)T/6" -1

read -p 'Please, enter your username: ' userinput
IFS=: read -r user pass uid gid name home shell < <(getent passwd $userinput)

if [ "$user" ] && [ "$user" = "$userinput" ]; then
    echo Good ${hope[hrclass]} ${name//,}
else
    echo "Unknown user:" $userinput
fi

无需解释:我会让您阅读 的手册页(man bash)并努力理解每个步骤。 (注意这个使用 bash 和所谓的 bashisms。)...也许改天,如果真的 cmets 要求的话。不过今天,我得走了……

【讨论】:

    猜你喜欢
    • 2016-08-06
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    • 1970-01-01
    相关资源
    最近更新 更多