问题描述
我正在尝试编写一个 bash 脚本,允许用户使用通配符传递目录路径.
I'm trying to write a bash script that allows the user to pass a directory path using wildcards.
例如
bash show_files.sh *
在此目录中执行时
drw-r--r-- 2 root root 4.0K Sep 18 11:33 dir_a
-rw-r--r-- 1 root root 223 Sep 18 11:33 file_b.txt
-rw-rw-r-- 1 root root 106 Oct 18 15:48 file_c.sql
会输出:
dir_a
file_b.txt
file_c.sql
现在的样子,它输出:
dir_a
show_files.sh
的内容:
#!/bin/bash
dirs="$1"
for dir in $dirs
do
echo $dir
done
推荐答案
父 shell,即调用 bash show_files.sh *
的那个,为你扩展了 *
.
The parent shell, the one invoking bash show_files.sh *
, expands the *
for you.
在你的脚本中,你需要使用:
In your script, you need to use:
for dir in "$@"
do
echo "$dir"
done
双引号确保文件名中的多个空格等得到正确处理.
The double quotes ensure that multiple spaces etc in file names are handled correctly.
如果您真的确定要让脚本扩展 *
,则必须确保将 *
传递给脚本(用引号括起来),就像在其他答案中一样),然后确保它在处理中的正确点被扩展(这不是微不足道的).那时,我会使用一个数组.
If you're truly sure you want to get the script to expand the *
, you have to make sure that *
is passed to the script (enclosed in quotes, as in the other answers), and then make sure it is expanded at the right point in the processing (which is not trivial). At that point, I'd use an array.
names=( $@ )
for file in "${names[@]}"
do
echo "$file"
done
我不经常使用没有双引号的 $@
,但这是一次或多或少正确的做法.棘手的部分是它不能很好地处理带有空格的通配符.
I don't often use $@
without the double quotes, but this is one time when it is more or less the correct thing to do. The tricky part is that it won't handle wild cards with spaces in very well.
考虑:
$ > "double space.c"
$ > "double space.h"
$ echo double space.?
double space.c double space.h
$
效果很好.但是尝试将它作为通配符传递给脚本,然后......好吧,我们只能说到那时它会变得很棘手.
That works fine. But try passing that as a wild-card to the script and ... well, let's just say it gets to be tricky at that point.
如果要单独提取$2
,那么可以使用:
If you want to extract $2
separately, then you can use:
names=( $1 )
for file in "${names[@]}"
do
echo "$file"
done
# ... use $2 ...
这篇关于如何将通配符参数传递给 bash 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!