如何在 Bash 中将字符串转换为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19107390/
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
How to convert string to integer in Bash?
提问by PhatHV
I have found many answers about this on StackOverflow but I can't apply them to my code.
我在 StackOverflow 上找到了很多关于这个的答案,但我无法将它们应用到我的代码中。
I used this command to get last day of current month:
我使用此命令获取当月的最后一天:
LASTDAY=`cal $(date +"%m %Y") | grep . | fmt -1 | tail -1`
then I use this code:
然后我使用这个代码:
for i in {1..${LASTDAY}}
do
# code for processing here!
done
But always get this warning: line 12: [: {1..31}: integer expression expected
但总是得到这个警告: 第 12 行:[: {1..31}: integer expression expected
and iis {1..31}but I expected iis a number in range [1,31]
并且i是{1..31}但我预计i是 [1,31] 范围内的数字
I have tried this:
我试过这个:
LASTDAY=$((LASTDAY+0))
LASTDAY=$( echo "$LASTDAY - 0" | bc )
LASTDAY=$(printf "%d" "$LASTDAY")
but it can't solve this problem. What's wrong in my code? and how to fix it?
但它不能解决这个问题。我的代码有什么问题?以及如何解决它?
Thanks in advanced.
提前致谢。
回答by CS Pei
Use the following instead of for i in {1..$Lastday}
使用以下代替 for i in {1..$Lastday}
for i in $(seq 1 ${LASTDAY}) ; do echo $i done
This will work.
这将起作用。