将数字转换为 bash 中的字符串枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2654894/
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
Convert numbers to enumeration of strings in bash
提问by User1
Using bash, I have a list of strings that I want to use to replace an int. Here's an example:
使用 bash,我有一个字符串列表,我想用它来替换 int。下面是一个例子:
day1=Monday day2=Tuesday day3=Wednesday day4=Thursday day5=Friday day6=Saturday day7=Sunday
If I have an int, $dow, to represent the day of the week, how do I print the actual string? I tried this:
如果我有一个 int $dow 来表示星期几,我该如何打印实际的字符串?我试过这个:
echo ${day`echo $dow`}
but get error of "bad substitution". How do I make this work? Note: I can change the $day variables to a list or something.
但得到“坏替代”的错误。我如何使这项工作?注意:我可以将 $day 变量更改为列表或其他内容。
采纳答案by Ignacio Vazquez-Abrams
Yes, it would be easiest to do this as an array:
是的,最简单的方法是将其作为数组执行:
day=([1]=Monday [2]=Tuesday ...)
echo "${day[dow]}"
回答by Pointy
case $dow in
[1234567]) eval echo '$day'$dow ;;
esac
I didn't want to get yelled at for an unsafe use of "eval" :-)
我不想因为不安全地使用“eval”而受到大吼:-)
There's probably a more "modern" way of doing this.
可能有一种更“现代”的方式来做到这一点。
回答by Jürgen H?tzel
You could use variable indirection:
您可以使用变量间接:
day_var=day$dow
echo ${!day_var}
But you should consider the use of arrays:
但是你应该考虑使用数组:
days=("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday")
echo ${days[$[$dow-1]]}
回答by user unknown
In June 1970 (you remember?) the month started with Monday:
1970 年 6 月(你还记得吗?)这个月从星期一开始:
for d in {1..7}
do
date -d 1970-06-0$d +%A
done

