如何在字符串变量中识别变量?

时间:2018-11-21 13:07:56

标签: string bash variables terminal gnu

我有以下bash脚本

#!/bin/bash
Sunday="
   '$number'apples
   '$number'oranges"
Monday="
   '$number'bananas"
# ... you get my drift
Wednesday="
   '$number'bananas
   '$number'oranges"
# ... Until Saturday

range={1..3}

function GetDay()
{
    if [ $(date +%A) == "Sunday" ]; then Day=$Sunday
    elif [ $(date +%A) == "Monday" ]; then Day=$Monday
    elif [ $(date +%A) == "Tuesday" ]; then Day=$Tuesday
    elif [ $(date +%A) == "Wednesday" ]; then Day=$Wednesday
    elif [ $(date +%A) == "Thursday" ]; then Day=$Thurday
    elif [ $(date +%A) == "Friday" ]; then Day=$Friday
    elif [ $(date +%A) == "Saturday" ]; then Day=$Saturday
    fi
}

function CountFruits()
{
    for number in $range
    do
        GetDay
        for day in $Day
        do
            echo $day
            done
        done
}

自星期三以来,我希望它输出

1 bananas
1 oranges
2 bananas
2 oranges
3 bananas
3 oranges

如何使此脚本起作用。识别我的范围似乎有些麻烦。输出

'' bananas
'' oranges

如果我直接将范围与for number in {1..3}而不是变量引用for number in $range一起使用

'' bananas
'' oranges
'' bananas
'' oranges
'' bananas
'' oranges

1 个答案:

答案 0 :(得分:2)

直接的问题是,您每天的变量$number立即扩展 ,因此Sunday的值实际上是

'' apples
'' oranges

您需要在外部上使用单引号以防止扩展;内引号只​​是常规字符。

但是,这是行不通的,因为变量中的字符串$number也是文字文本;当$number$Day扩展时,它不会使用当前的$day扩展。

您需要的是一个功能:

dailyList () {
  # $1 - day of the week
  # $2 - a number
  case $1 in
    Sunday) fruits=(apples oranges) ;;
    Monday) fruits=(bananas) ;;
    # etc
  esac

  for f in "${fruits[@]}"; do
    printf '%d %s' "$2" "$f"
  done
}

然后,从您的循环中调用它:

CountFruits () {
  for number in "$@"
  do
    dailyList "$(date +%A)" "$number"
  done
}

CountFruits {1..3}