在 bash 脚本中获取星期几

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22956516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:47:08  来源:igfitidea点击:

Get Day Of Week in bash script

bashsed

提问by bbholzbb

I want to have the day of week in the variable DOW.

我想在变量中包含星期几DOW

So I use the following bash-script:

所以我使用以下 bash 脚本:

DOM=$(date +%d)
DOW=($($DOM % 7) ) | sed 's/^0*//'

Unfortunately there I get this error: bash: 09: command not found. The expected result is 2 ( 9 % 7 = 2) in the variable $DOW.

不幸的是,我收到此错误:bash: 09: command not found。变量中的预期结果是 2 ( 9 % 7 = 2) $DOW

How can I get this working? It works for the days 1-8 but because of the C-hex, there is no number over 8 available and the following message appears: bash: 09: value too great for base (error token is "09").

我怎样才能让它工作?它适用于 1-8 天,但由于 C-hex,没有超过 8 的可用数字,并显示以下消息:bash: 09: value too great for base (error token is "09")

回答by hek2mgl

Use %u. Like this:

使用%u. 像这样:

DOW=$(date +%u)

From the man page:

手册页

%u day of week (1..7); 1 is Monday

%u 星期几 (1..7); 1 是星期一

回答by glenn Hymanman

Using a different %-specifier is the real answer to your question. The way to prevent bash from choking on invalid octal numbers is to tell it that you actually have a base-10 number:

使用不同的 % 说明符是您问题的真正答案。防止 bash 因无效八进制数而窒息的方法是告诉它您实际上有一个以 10 为基数的数字:

$ DOM=09
$ echo $(( DOM % 7 ))
bash: 09: value too great for base (error token is "09")
$ echo $(( 10#$DOM % 7 ))
2

回答by Ronald Hofmann

This works fine here

这在这里工作正常

#!/bin/sh
DOW=$(date +"%a")
echo $DOW

回答by LordWilmore

I've always found that using 'let' is the most simple solution for BASH. So that would be:

我一直发现使用“让”是 BASH 最简单的解决方案。所以那将是:

let "DOW = DOM % 7"

回答by devnull

You can use the -flag:

您可以使用-标志:

DOM=$(date +%-d)
             ^

which would prevent the day from being padded with 0.

这将防止一天被填充0

From man date:

来自man date

   -      (hyphen) do not pad the field

Observe the difference:

观察差异:

$ DOM=$(date +%d)
$ echo $((DOM % 7))
bash: 09: value too great for base (error token is "09")
$ DOM=$(date +%-d)
$ echo $((DOM % 7))
2