1

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
2

2 Answers 2

3

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

2 Comments

Would just like to note that this script returns the following, imgur.com/a/VysKD3Y. Otherwise, it works :D
@SamuelCorsi-House enter the number from the selection :)
1

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)

4 Comments

You don't fill an array with ls
@LéaGris can you help understand why that's a bad practice?
Because jars=(*.jar) does the same thing without spawning ls, and keeps spaces in filenames intact.
Thanks @oguzismail.

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.