Adding arguments into array by loop

I want to create script which will create directories. User has to pick how many directories he wants to create, and then has to name those directories.

I already have something like this, but I stuck and don't know how to add arguments into array by loop..

Could you tell me how it should be?

#!/bin/bash

read year
read group
read student


subjects=()
for directories in ${subjects[*]}
do
  mkdir -p /home/uczelnia/$year/$group/$student/$directories
done

2 answers

  • answered 2018-01-14 00:40 John1024

    To have the user enter subjects and save them in array subjects, run:

    echo "Enter subjects, one per line, type Ctrl-D when done:"
    readarray -t subjects
    

    Running the above code and entering three subject:

    Enter subjects, one per line, type Ctrl-D when done:
    Math
    History
    Biology
    

    (At the new line after biology, we can't see it but the user typed Ctrl-D.)

    We can verify that subjects is indeed the array we want by examining it with declare -p:

    $ declare -p subjects
    declare -a subjects=([0]=$'Math\n' [1]=$'History\n' [2]=$'Biology\n')
    

    Aside

    When you use reference variables, they should be in double-quotes to prevent word-splitting and pathname expansion. Thus, replace:

    for directories in ${subjects[*]}
    do
      mkdir -p /home/uczelnia/$year/$group/$student/$directories
    done
    

    With:

    for directories in "${subjects[@]}"
    do
      mkdir -p "/home/uczelnia/$year/$group/$student/$directories"
    done
    

    Whole script

    read -p "Enter year: " year
    read -p "Enter group: " group
    read -p "Enter student: " student
    echo "Enter subjects, one per line, type Ctrl-D when done:"
    readarray -t subjects
    for directories in "${subjects[@]}"
    do
      mkdir -p "/home/uczelnia/$year/$group/$student/$directories"
    done
    

  • answered 2018-01-14 00:40 PesaThe

    No need for arrays here. This might be what you are trying to do:

    #!/usr/bin/env bash
    
    read -rp "Enter year: " year
    IFS= read -rp "Enter group: " group
    IFS= read -rp "Enter student: " student
    
    read -rp "Enter number of dirs: " number
    
    for (( i=0; i<number; i++ )); do
        IFS= read -rp "Enter folder #$((i+1)): " folder
        mkdir -p "/home/uczelnia/$year/$group/$student/$folder"
    done