如何在Bash中将目录列表存储到数组中(然后将其打印出来)?

qod*_*nja 26 arrays directory bash

我想写一个shell脚本来显示用户输入的目录列表,然后让用户根据有多少目录选择一个索引号的目录

我认为这是某种数组操作,但我不知道如何在shell脚本中执行此操作

例:

> whichdir
There are 3 dirs in the current path
1 dir1
2 dir2
3 dir3
which dir do you want? 
> 3
you selected dir3!
Run Code Online (Sandbox Code Playgroud)

Pau*_*ce. 39

$ ls -a
./ ../ .foo/ bar/ baz qux*
$ shopt -s dotglob
$ shopt -s nullglob
$ array=(*/)
$ for dir in "${array[@]}"; do echo "$dir"; done
.foo/
bar/
$ for dir in */; do echo "$dir"; done
.foo/
bar/
$ PS3="which dir do you want? "
$ echo "There are ${#array[@]} dirs in the current path"; \
select dir in "${array[@]}"; do echo "you selected ${dir}"'!'; break; done
There are 2 dirs in the current path
1) .foo/
2) bar/
which dir do you want? 2
you selected bar/!
Run Code Online (Sandbox Code Playgroud)

  • 'select`为+1.它是人们经常试图重新发明的隐藏的bash宝藏之一,因为他们不知道它存在 (4认同)

Joh*_*ica 23

数组语法

假设您将目录存储在数组中:

dirs=(dir1 dir2 dir3)
Run Code Online (Sandbox Code Playgroud)

你可以这样获得数组的长度:

echo "There are ${#dirs[@]} dirs in the current path"
Run Code Online (Sandbox Code Playgroud)

您可以这样循环:

let i=1

for dir in "${dirs[@]}"; do
    echo "$((i++)) $dir"
done
Run Code Online (Sandbox Code Playgroud)

假设您已获得用户的答案,您可以按如下方式对其进行索引.请记住,数组是从0开始的,因此第3个条目是索引2.

answer=2

echo "you selected ${dirs[$answer]}!"
Run Code Online (Sandbox Code Playgroud)

无论如何,如何将文件名转换为数组?这有点棘手.如果你有find这可能是最好的方式:

readarray -t dirs < <(find . -maxdepth 1 -type d -printf '%P\n')
Run Code Online (Sandbox Code Playgroud)

-maxdepth 1停止从通过子目录寻找发现,-type d告诉它找到的目录和文件跳过,并且-printf '%P\n'告诉它没有导致打印目录名./它通常喜欢打印.


Jes*_*ter 5

#! /bin/bash

declare -a dirs
i=1
for d in */
do
    dirs[i++]="${d%/}"
done
echo "There are ${#dirs[@]} dirs in the current path"
for((i=1;i<=${#dirs[@]};i++))
do
    echo $i "${dirs[i]}"
done
echo "which dir do you want?"
echo -n "> "
read i
echo "you selected ${dirs[$i]}"
Run Code Online (Sandbox Code Playgroud)