Samuel Corsi-House
Samuel Corsi-House

Reputation: 347

Bash array not working providing expected length

I'm trying to get all jar files in a directory and store them in an array. Currently, it's not working as expected and I think it's because it's an array inside an array? Let me know if it is and how would I fix it. When I echo the length of the array, it's always 1 yet when I loop over it, it can have more than 1 file.

Code:

#!/bin/bash

cd "/home/ubuntu/RLCraft" || exit 1
jars=("$(ls *.jar)")
echo "${#jars[@]}" -gt "1"
if (("${#jars[@]}" > "1")); then
    echo "yes"
else
    echo "no"
fi
for i in "${jars[@]}"; do
    echo "$i"
done
if [ "${#jars[@]}" -gt 1 ]; then
    echo "Choose a server jar:"
    for i in "${jars[@]}"; do
        echo "$i"
    done
    read -r serverJar
else
    serverJar="${jars[0]}"
fi

Expected output:

yes
magma-server.jar
minecraft_server.1.12.2.jar

Resulting output:

no
magma-server.jar
minecraft_server.1.12.2.jar

Upvotes: 1

Views: 77

Answers (2)

Léa Gris
Léa Gris

Reputation: 19545

To fill an array from all .jar files just do:

array=(*.jar)

Here is your fixed script:

#!/usr/bin/env bash

shopt -s nullglob

cd "/home/ubuntu/RLCraft" || exit 1

jars=(*.jar)

if [ "${#jars[@]}" -gt 1 ]; then
  echo "Choose a server jar:"
  selections=("${jars[@]}" 'Quit')
  select serverJar in "${selections[@]}"; do
    case $serverJar in
      '')
        echo "Invalid choice" >&2
        ;;
      'Quit')
        echo "Goodby!"
        exit
        ;;
      *)
        echo "You have selected: $serverJar"
        break
        ;;
    esac
  done
else
  echo "No jar found in $PWD" >&2
fi

Upvotes: 3

Hydes
Hydes

Reputation: 668

The problem is while creating the array.

jars=("$(ls *.jar)")

When you do this, the quotes is causing the whole list to be interpreted as one single element. Remove the quotes as below to resolve the issue:

jars=($(ls *.jar))

Edit:

As mentioned in comments a better way is without the ls as

jars=(*.jar)

Upvotes: 1

Related Questions