So I have a bash script which will scan a directory and run a function on a selected input.
echo -n " ------------------------------------------------------- `hostname` Menu ------------------------------------------------------- Choose your desired Host: ` i=1 for D in /var/www/*.*/; do if [[ -d $D ]]; then Hosts[$i]=$D echo $i') ' $D i=$(($i+1)) fi done ` " read -p "Select: " Input Directory="${Hosts[$Input]}"; ChangePerms;
It seems that for some reason, the key is not setting from the array properly.
Choose your desired Host: 1) /var/www/example1.com/ 2) /var/www/example2.com/ + read -p 'Select: ' Input Select: 1 + Directory= + ChangePerms + true
What am I missing? All help is much appreciated!
EDIT: As a side note, I can run the commands separately and get results.
root@web005:/# i=1 root@web005:/# for D in /var/www/*.*/; > do > if [[ -d $D ]]; then > Hosts[$i]=$D > echo $i') ' $D > i=$(($i+1)) > fi > done 1) /var/www/example1.com/ 2) /var/www/example2.com/ root@web005:/# read -p "Select: " Input Select: 1 root@web005:/# Directory="${Hosts[$Input]}"; root@web005:/# echo $Directory /var/www/example1.com/ root@web005:/#
Here is the working code for those who get stuck like me:
echo -n " ------------------------------------------------------- `hostname` Menu ------------------------------------------------------- Choose your desired Host: " i=1 for D in /var/www/*.*/; do if [[ -d $D ]]; then Hosts[$i]=$D echo $i') ' $D i=$(($i+1)) fi done read -p "Select: " Input Directory="${Hosts[$Input]}"; ChangePerms;
Advertisement
Answer
Your problem is:
` i=1 for D in /var/www/*.*/; do if [[ -d $D ]]; then Hosts[$i]=$D echo $i') ' $D i=$(($i+1)) fi done `
which executes in a subshell
. Therefore, the remainder of your script has no idea what Hosts
is. (in other words, Hosts
is empty in the main body of your script). Fill Hosts
before you present your menu.