我想创建将创建目录的脚本。 用户必须选择他想要创建的目录数,然后必须为这些目录命名。
我已经有类似这样的东西了,但我卡住了,不知道如何通过循环将参数添加到数组中..
你能告诉我它应该如何吗?
#!/bin/bash
read year
read group
read student
subjects=()
for directories in ${subjects[*]}
do
mkdir -p /home/uczelnia/$year/$group/$student/$directories
done
答案 0 :(得分:0)
要让用户输入主题并将其保存在数组subjects
中,请运行:
echo "Enter subjects, one per line, type Ctrl-D when done:"
readarray -t subjects
运行上述代码并输入三个主题:
Enter subjects, one per line, type Ctrl-D when done:
Math
History
Biology
(在生物学后的新行,我们看不到它,但用户输入了Ctrl-D。)
我们可以通过subjects
检查declare -p
是否确实是我们想要的数组:
$ declare -p subjects
declare -a subjects=([0]=$'Math\n' [1]=$'History\n' [2]=$'Biology\n')
当您使用引用变量时,它们应该是双引号以防止分词和路径名扩展。因此,替换:
for directories in ${subjects[*]}
do
mkdir -p /home/uczelnia/$year/$group/$student/$directories
done
使用:
for directories in "${subjects[@]}"
do
mkdir -p "/home/uczelnia/$year/$group/$student/$directories"
done
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
答案 1 :(得分:0)
这里不需要数组。这可能就是你想要做的事情:
#!/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=1; i<=number; i++ )); do
IFS= read -rp "Enter folder #$i: " folder
mkdir -p "/home/uczelnia/$year/$group/$student/$folder"
done