Assuming that I have a directory which contains decades of subdirectories:
$ ls -d /very/long/path/*/
adir1/ adir2/ b2dir/ b3dir/ k101/ k102/ k103/ k104/ k220/ k221/ k222/ etc
I would like to loop over a selection of directories which will be defined "dynamically" based on the answer given by the user and it will contain wildcards. For example (the code that doesn't work):
$ cat my_script.sh
DATADIR="/very/long/path"
echo -n "Select dirs to involve: "
read dirlist
for DIR in "$dirlist"; do
echo $DATADIR/$DIR
[do stuff]
...
done
What would be desired is the following:
$ ./my_script.sh
Select dirs to involve: a* k10?
/very/long/path/adir1
/very/long/path/adir2
/very/long/path/k101
/very/long/path/k102
/very/long/path/k103
/very/long/path/k104
Any hint?
答案 0 :(得分:0)
一个可能的解决方案是使用find
:
#!/bin/bash
DATADIR="/very/long/path"
echo -n "Select matching expression: "
IFS= read -r dirlist
while IFS read -r -d '' DIR; do
echo "$DIR"
[do stuff]
...
done < <(find "$DATADIR" -path "$dirlist" -print0)
我建议您阅读find
的联机帮助页,因为匹配会占用斜线,并且可能不像您习惯使用shell globbing那样。
请注意,使用-print0
和read -d''
可以确保处理具有有趣名称(空白,换行符)的文件而不会出现问题。
如果您希望能够同时处理多个表达式输入,则必须执行以下操作:
#!/bin/bash
DATADIR="/very/long/path"
echo -n "Select matching expression: "
IFS= read -r -a dirlist_array
for dirlist in "${dirlist_array[@]}" ; do
while IFS read -r -d '' DIR; do
echo "$DIR"
[do stuff]
...
done < <(find "$DATADIR" -path "$dirlist" -print0)
done
答案 1 :(得分:0)
不确定这是否会遇到问题,但要给它一个旋转:
DATADIR="/very/long/path"
read -r -p "Select dirs to involve: " -a dirs
cd $DATADIR
for dir in ${dirs[@]}
do
echo "$dir"
done
让阵列不加引号可以使球体扩展。
更新:双循环以允许使用目录位置
DATADIR="/very/long/path"
read -r -p "Select dirs to involve: " -a dirs
for item in "${dirs[@]}"
do
for dir in "$DATADIR/"$item
do
echo "$dir"
done
done