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 so on

I need to take this Year.txt as reference in my another script some sample.sh

sample.sh

source /home/user/Year.txt
d=cp $filename $1
echo $d

sample.sh Year2000(passing Year2000 as first argument)

**I need to cut the second part after = if I pass Year2000 as my argument and paste this 1/2/3/4/ in my statement

**I need to cut the second part after = if I pass Year2001 as my argument and paste this 5/6/7/8/ in my copy statement etc..

I need output like this:

Input1 sample.sh Year2000

Output: cp somefile.txt 1/2/3/4/

Input2: sample.sh Year2001

Output: cp somefile.txt 5/6/7/8/

In Short -- I need to take the reference from another file and generate the copy statement

1 Answers

0
Charles Duffy On Best Solutions

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]}"