2

I am very new to bash scripting but am having trouble accessing an array. (or what I believe to be an array) I am using a file glob to get the contents of an array.

I simply want to print each file and then allow the user to pick one based on its index. However I am noticing that everything is stored in the first element of the array. What am I missing? Is file globbing not the best idea here for what I want?

files=templates/*.tex
fnum=0
for file in $files
do
        echo $fnum : $file
        # bash expression is ((expression)) $(( expression )) expects a command
        (( fnum++ ))
done
read -p "Which file would you like to include: " answer
if [ $answer -ge 0 ] && [ $answer -lt $fnum ]
then
        echo ${$files[0]}
else
        echo bad range...
        exit 1
fi
1
  • Aside: There are a lot of bugs in here that shellcheck.net would find automatically. Commented Jul 28, 2015 at 17:59

2 Answers 2

7

files is not an array; files=( templates/*.tex ) is.

files=( templates/*.tex )
fnum=0
for file in "${files[@]}"
do
        echo "$fnum : $file"
        (( fnum++ ))
done
read -p "Which file would you like to include: " answer
if [ "$answer" -ge 0 ] && [ "$answer" -lt "$fnum" ]
then
        echo "${files[answer]}"
else
        echo bad range...
        exit 1
fi

More idiomatically in bash (not identical, but provides the same basic functionality much more concisely):

PS3="Which file would you like to include: "
select answer in "${files[@]}"; do
    echo "$answer"
    break
done
Sign up to request clarification or add additional context in comments.

7 Comments

As an aside, you can get rid of fnum, the read command, and the range check using the select command in bash.
"${files[@]} what does this mean?
also for the ${$files[answer]} line it is saying its a bad substitution. $answer gets the same result
@9er, ${files[$answer]} is the correct way to write that.
@chepner, ...btw, you have rather a lot of quoting bugs here. Mind if I step in and fix them up?
|
1

Your files variable is a string, try files=( templates/*.tex ) if I am not mistaking this should make an array of the files

To iterate over the array you should use for file in "${files[@]}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.