简体   繁体   中英

Assigning values to an array in Bash shell script

I've got a plain text file containing track titles & artists separated by a dash. I want to put all the titles into one array ( TRK_TITLE[] ). At the same time create an array of artists ( ARTIST[] ). Below is the code I'm using:

CTR=0
# Read in the track title file
while read line

do 

# Add to the counter
    CTR=$((CTR + 1))

# Get the track number
    TRK_NUM[$CTR]=$CTR

# VARIOUS is set by command line parameter
if [ $VARIOUS = "FALSE" ]
then
# -- THIS BIT WORKS! ------------------------------
TRK_TITLE[$CTR]=${line}
# ARTISTS determined by grandparent directory name.
ARTIST[$CTR]="$ARTISTS"

# THE BIT THAT DOESN'T WORK AS IT APPEARS --------- 
else
# VARIOUS has been set to TRUE
# Get the track title
# 1st, Make sure I'm dealing with something sensible
echo "$line"
# Get the length of the line,
# just for information
total_len=${#line}
# Find the position of the "-"
dash_pos=`expr index "$line" -`

# These lines prove that the syntax works
echo "${line:0:$dash_pos - 2}"

echo "${line:$dash_pos + 1}"

echo $total_len "--" $dash_pos 
# Now add to arrays
TRK_TITLE[$CTR]="${line:0:$dash_pos -2}"
#TRK_TITLE="${line:0:$dash_pos -2}"

ARTIST[$CTR]="${line:$dash_pos + 1}"
#ARTIST="${line:$dash_pos + 1}"

#Now to see the output
echo $TRK_TITLE[$CTR] "is Track"
#echo "$TRK_TITLE is Track"

echo $ARTIST[$CTR] "is Artist"
#echo "$ARTIST is Artist"

fi

# keep going until the end
# Variable name used for input file
done < "$FYL_2_USE"

When the hashes are where they are the output is thus:

Dedicated to the One I Love - The Mamas and The Papas

Dedicated to the One I Love

The Mamas and The Papas

53 -- 29

[19] is Track

[19] is Artist

If the hashes are swapped on the variable and echo statements, the output is thus:

Dedicated to the One I Love - The Mamas and The Papas

Dedicated to the One I Love

The Mamas and The Papas

53 -- 29

Dedicated to the One I Love is Track

The Mamas and The Papas is Artist

Shell is Gnu Bash V4.1.0(2)

If you replace:

echo $TRK_TITLE[$CTR] "is Track"
echo $ARTIST[$CTR] "is Artist"

with:

echo ${TRK_TITLE[$CTR]} "is Track"
echo ${ARTIST[$CTR]} "is Artist"

your script will work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM