Shell脚本中判断星期几的if/else语句不生效如何解决?
Shell脚本问题排查结果
问题根本原因
你的代码在[[ ]]判断条件中没有给变量current_day_of_week加上变量取值前缀$,导致Shell没有解析该变量的实际值,而是直接把current_day_of_week当成普通字符串和1做对比,判断条件永远不成立,所以不管是不是周一,都会执行else分支的逻辑。
修正后的代码
current_time=$(date +"%T"); current_day_of_week="$(date +'%u')"; # 给变量加$前缀获取实际值 if [[ $current_day_of_week == 1 ]]; then echo "Setting max time to 03:00:00" && max_time="03:00:00"; else echo "Setting max time to 01:30:00" && max_time="01:30:00"; fi;
补充说明
- Bash的
[[ ]]条件判断语法中,只有使用$前缀才会读取变量的实际存储值,未加$的标识符会被识别为普通字符串 - 你也可以简化写法,省去单独声明
current_day_of_week变量的步骤,直接把取值逻辑写在判断条件里:
if [[ $(date +'%u') == 1 ]]; then echo "Setting max time to 03:00:00" && max_time="03:00:00" else echo "Setting max time to 01:30:00" && max_time="01:30:00" fi
内容的提问来源于stack exchange,提问作者owsiankasb
相关产品推荐
相关产品推荐

