我如何通过通配符参数来一个bash文件 [英] How do I pass a wildcard parameter to a bash file

查看:125
本文介绍了我如何通过通配符参数来一个bash文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个bash脚本,允许用户通过使用通配符的目录路径。

例如,

 庆典show_files.sh *

在此目录中执行

  DRW-R  -  R-- 2根根4.0K 09月18日11:33 dir_a
-rw-R - R-- 1根根223 09月18日11:33 file_b.txt
-rw-RW-R-- 1根106根10月18日15:48 file_c.sql

将输出:

  dir_a
file_b.txt
file_c.sql

它是现在的方式,它输出:

  dir_a

内容 show_files.sh

 #!/斌/庆典迪尔斯=$ 1在$迪尔斯DIR

    回声$ DIR
DONE


解决方案

父shell,一个援引庆典show_files.sh * ,扩展了 * 为您服务。

在你的脚本,你需要使用:

 在$ @DIR

    回声$目录
DONE

双引号确保多个空格等文件名是正确处理。

另请参见如何循环参数在 庆典 shell脚本


可能造成混乱编

如果你真的确定要拿到剧本扩大 * ,你必须确保 * 传递给脚本(用引号括起来,如在其他的答案),然后确保它在加工右键点(这是不平凡的)展开。在这一点上,我会使用一个数组。

  =名称($ @)
在文件$ {名称[@]}

    回声$文件
DONE

我不经常使用 $ @ 没有双引号,但是这一次,当它或多或少是正确的事情。最棘手的部分是,它不会很好地处理通配符用空格。

考虑:

  $> 双space.c
$> 双space.h
$呼应双\\ \\空间?
双space.c双space.h
$

这工作正常。但经过尝试,作为一个外卡到脚本和......好吧,让我们只说它得到是棘手的在这一点上。

如果要提取 $ 2 分开,那么你可以使用:

  =名称($ 1)
在文件$ {名称[@]}

    回声$文件
DONE
#...使用$ 2 ......

I'm trying to write a bash script that allows the user to pass a directory path using wildcards.

For example,

bash show_files.sh *

when executed within this directory

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

would output:

dir_a
file_b.txt
file_c.sql

The way it is right now, it outputs:

dir_a

contents of show_files.sh:

#!/bin/bash

dirs="$1"

for dir in $dirs
do
    echo $dir
done

解决方案

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.

See also How to iterate over arguments in a bash shell script.


Potentially confusing addendum

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.

Consider:

$ > "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.

If you want to extract $2 separately, then you can use:

names=( $1 )
for file in "${names[@]}"
do
    echo "$file"
done
# ... use $2 ...

这篇关于我如何通过通配符参数来一个bash文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆