Use key/value data from a file in a shell script

后端 未结 1 1416
醉梦人生
醉梦人生 2020-12-22 06:07

I have a file called Year.txt

Year2000= 1/2/3/4/
Year2001= 5/6/7/8/
Year2002= 9/10/11/12/
....
....
....
Year2020= 100/101/102/

etc and s

相关标签:
1条回答
  • 2020-12-22 06:41

    Don't source files that aren't legal bash code. In this case, an associative array lets you store as many key/value pairs as you need inside a single variable.

    #!/usr/bin/env bash
    case $BASH_VERSION in ''|[123].*) echo "ERROR: Needs bash 4.0 or newer" >&2; exit 1;; esac
    
    year_name=$1
    file_name=$2
    
    [[ $file_name ]] || { echo "Usage: $0 year-name file-name" >&2; exit 1; }
    
    # Read year.txt, and generate a map
    declare -A dirs_by_year=( )
    while IFS='= ' read -r k v; do
      dirs_by_year[$k]=$v
    done <Year.txt
    
    if ! [[ ${dirs_by_year[$year_name]} ]]; then
      echo "ERROR: User specified year $1, but input file does not have a directory for it" >&2
      echo "       ...defined years follow:" >&2
      declare -p dirs_by_year >&2  # print array definition to show what we read
      exit 1
    fi
    
    # generate and write a cp command
    printf '%q ' cp "$file_name" "${dirs_by_year[$year_name]}"
    
    0 讨论(0)
提交回复
热议问题