Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading