1

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]"
1
  • {0..$num} doesn't work in bash as braces will be expanded before parameters. Commented Jun 3, 2016 at 16:06

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

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.