Bash's array strange behavior with ls

DISCLAIMER: I’m fairly new to bash scripting, and it may be some technicality that I’m not aware of.


In a nutshell, I want to ls a directory and dynamically add a case switch to each one of the outputed file names, regardless of array size the size.

The purpose of my script is to get the name of the file and then update a line in my .zshrc with sed (Which i left out this example as it falls off topic)

Code:

#!/bin/bash

CHOICE=$(ls $HOME/some/dir/here/)

select opt in Quit ${CHOICE[@]}; do
    case "$opt" in
    "Quit")
        echo "Quitting..."
        exit 0
        ;;
    esac
    for ((i = 0; i < ${#CHOICE[@]}; i++)); do
        case "$opt" in
        ${CHOICE[i]})
            echo "You choose \"${CHOICE[i]}\""
            exit 0
            ;;
        esac
    done
    case "$opt" in
    *)
        echo "Invalid Input. Exiting without changes..."
        exit 0
        ;;
    esac
done
exit 0

Expected behavior:

1) Quit
2) some
3) options
4) here
#? 2
You choose "some"

Actual behavior:

1) Quit
2) some
3) options
4) here
#? 3
Invalid Input. Exiting without changes...

Now, when i change:

CHOICE=$(ls $HOME/some/dir/here/)

to a static array, like:

CHOICE=("some" "options" "here")

It works just fine, but, of curse, a static array is not what i want.

>Solution :

Like this:

CHOICE=( $HOME/some/dir/here/* )

select opt in Quit "${CHOICE[@]}"; do 

This use glob

Thanks to not parsing ls output

Leave a Reply