Sunday, February 27, 2022

[SOLVED] How do I write a one-liner cd command for the following case?

Issue

I have 2 directories
testing_dir
testing_dir_win

So I need to cd to testing_dir. But here is the case

the directories can be
/> testing_dir or testing_dir-2.1.0
testing_dir_win or testing_dir_win-1.3.0

and my script should only take testing_dir or testing_dir-2.1.0 (based on which is available)

I have the long way of writing it:

str=`ls folder_name|grep ^testing_dir`
arr=(${str//" "/ })
ret=""
for i in "${arr[@]}"
do
    if [[ $i != *"testing_dir_win"* ]] ; then
            ret=$i
    fi
done

but is there a one-liner for this problem? something like cd testing_dir[\-]?(This doesn't work by the way).


Solution

If your script contains

shopt -s extglob

you can use:

cd testing_dir?(-[[:digit:]]*) || exit

...if you have a guarantee that only one match will exist.

Without that guarantee, you can directly set

arr=( testing_dir?(-[[:digit:]]*) )
cd "${arr[0]}" || exit


Answered By - Charles Duffy
Answer Checked By - David Goodson (WPSolving Volunteer)