Eric_Xerces
Eric_Xerces

Reputation: 13

Using indexed array elements to choose directories in bash

I am trying to write a bash function that will list each subdirectory and file in the current directory and index them in an array, then it will cd into the desired directory by accessing that index in the array. When I echo the array at index 8 it outputs 0[8]. why is it not outputting the directory name?

num=0

for dir in  ./*
do
  echo -n $num
  echo -n ":  "
  echo $( basename $dir  )
  num=$(($num+1));
done

declare -a array=( $(for i in {0..$num}; do echo 0; done) )

for dir in  ./*
do
  for i in {0..$num};
  do
    if [ -z $array[$num] ]; then
       $dir= basename $dir
       $array[$num]= $num
    fi
    break

  done
done

echo "Enter the directory number: "
read requested

cd "$array[$requested]"

Upvotes: 1

Views: 133

Answers (1)

jbe
jbe

Reputation: 1792

you can initialize an array and add items to like this

ARRAY=()  
ARRAY+=('foo')  
ARRAY+=('bar')

to retrieve the value you have to use curly brackets

echo ${ARRAY[0]}

so the following should work

#!/bin/bash

num=0
for dir in  ./*
do
  echo $num": " $dir
  num=$(($num+1));
done

ARRAY=()
for dir in  ./*
do
  ARRAY+=("$dir")
done


echo "Enter the directory number: "
read requested

echo "you entered " $requested
echo "go to" ${ARRAY[$requested]}

cd "${ARRAY[$requested]}"
pwd

Upvotes: 2

Related Questions