[英]Bash script: expansion of argument not using $@ or $*
使用$@
您可以对bash中的文件列表执行操作。 例:
script.sh:
#!/bin/bash
list=$@
for file in $list; do _commands_; done
然后我可以用这个程序调用
~/path/to/./script dir1/{subdir1/*.dat,subdir2/*}
这个参数将扩展为许多成为$list
的参数。 但现在我想要其他参数,比如1美元,2美元,这个名单是3美元。 所以我想在脚本中发生dir1/{subdir1/*.dat,subdir2/*}
扩展,而不是成为很多参数。 在命令行上,您可以执行以下操作:
find dir1/{subdir1/*.dat,subdir2/*}
并获得所需的输出,即文件列表。 所以我尝试过这样的事情:
arg1=$1
arg2=$2
list=$(find $3)
for file in $list; do _commands_; done
...
电话:
~/path/to/./script arg_1 arg_2 'dir1/{subdir1/*.dat,subdir2/*}'
但没有成功。 关于如何将此列表扩展为脚本内的变量的一些帮助将非常感激!:)
编辑:所以下面的答案给出了使用这些命令的解决方案:
arg1="$1"
arg2="$2"
shift 2
for f in "$@"; do echo "processing $f"; done;
但出于好奇,是否仍然可以将字符串dir1/{subdir1/*.dat,subdir2/*}
传递给脚本内的find
命令(或任何指向同一端的方法),而不使用$@
,并获取列表那样? 这可能是有用的,例如,如果最好使列表不是第一个或最后一个参数,或者在某些其他情况下,即使它需要转义字符或引用参数。
您可以在脚本中使用此代码:
arg1="$1"
arg2="$2"
shift 2
for f in "$@"; do echo "processing $f"; done;
然后将其称为:
~/path/to/script arg_1 arg_2 dir1/{subdir1/*.dat,subdir2/*}
使用shift 2
将位置参数移动2个位置,从而使$3
为$1
, $4
为$2
等。然后您可以直接调用$@
来迭代其余参数。
按照help shift
:
shift: shift [n]
Shift positional parameters.
Rename the positional parameters $N+1,$N+2 ... to $1,$2 ... If N is
在调用脚本之前,shell将执行shell扩展。 这意味着你必须引用/转义参数。 在脚本中,您可以使用eval
执行扩展。
#!/bin/bash
arg1="$1" ; shift
arg2="$2" ; shift
eval "list=($@)"
for q in "${list[@]}" ; do echo "$q" ; done
$ ./a 123 456 'a{b,c}' 'd*'
ab ac d.pl docs
我没有看到在您的示例中在脚本内部进行扩展的重点。
#!/bin/bash
arg1="$1" ; shift
arg2="$2" ; shift
list=("$@")
for q in "${list[@]}" ; do echo "$q" ; done
要不就
#!/bin/bash
arg1="$1" ; shift
arg2="$2" ; shift
for q in "$@" ; do echo "$q" ; done
$ ./a 123 456 a{b,c} d*
ab
ac
d.pl
docs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.