Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从传递的参数展开BASH参数_Bash_Shell_Expansion - Fatal编程技术网

从传递的参数展开BASH参数

从传递的参数展开BASH参数,bash,shell,expansion,Bash,Shell,Expansion,我对以GNU bash版本4.2.25(1)-发行版(x86_64-pc-linux-GNU)运行的/bin/bash脚本中的shell参数扩展有问题 我只在传递的第一个参数中添加了$path 对于上面的cmd ln,这意味着我得到了$path/file*,它被成功地扩展了,&我得到了预期的3个文件,但是剩余的参数被完全按照传递的方式(即my_files*log*)进行了回显,没有$path,因此星号扩展失败 关于如何绕过此问题的建议将不胜感激。如果您只需要将路径附加到其余的每个参数,请执行以下

我对以GNU bash版本4.2.25(1)-发行版(x86_64-pc-linux-GNU)运行的/bin/bash脚本中的shell参数扩展有问题

我只在传递的第一个参数中添加了$path

对于上面的cmd ln,这意味着我得到了$path/file*,它被成功地扩展了,&我得到了预期的3个文件,但是剩余的参数被完全按照传递的方式(即my_files*log*)进行了回显,没有$path,因此星号扩展失败


关于如何绕过此问题的建议将不胜感激。

如果您只需要将
路径
附加到其余的每个参数,请执行以下操作:

for f in ${find_these[@]} ; do
  echo f is $path/$f
done

我不确定变量
$file
是什么,但看起来您可能打算编写
$f
,而不是
$file
,因为我看不出有其他原因让您使用该变量进行循环

for f in $path/${find_these[@]} ; do
  echo f is $f
done

在展开模式之前,您只需转到目录即可(无需将
$@
分配给变量):

由于您在脚本中执行
cd
,因此外部环境保持在相同的环境中

例如:

$ cd -- "$(mktemp --directory)"
$ cat test.sh 
path="$1"
shift
cd "$path"
for file in $@
do
    echo "Found file: $file"
done
$ mkdir foo
$ touch foo/a foo/abc
$ sh test.sh foo a*
Found file: a
Found file: abc

如果要在遍历数组之前预先指定每个文件的路径,可以这样做

#!/bin/bash

path=$1
shift
find_these=( "$@" )

for f in "${find_these[@]/#/$path/}" ; do
  echo "f is $f"
done

我在OS X 10.9上的GNU bash 4.2.45(2)上测试了这一点,它可以工作。

@gniourf\u gniourf:但它不能扩展全局;它只在路径前面加上前缀。您需要删除
“${find_this[@]/#/$path}”
中的引号,以实现OP的要求。在可能的范围内。@rici我认为在调用脚本时,globs已经被扩展了(这就是我的理解,因为OP使用
explore\u asterisk\u expansion.bash path/to/other/files file*my\u files*log*
调用脚本,此时bash进行全局扩展,脚本
explore\u asterisk\u expansion.bash
扩展了所有需要的参数).No?@gniourf\u gniourf:OP想要在
path/to/other/files
中展开
文件*
,因此它依赖于调用脚本时不展开
文件*
(显然是一个设计缺陷)。从OP中可以看出:“对于上面的cmd ln,这意味着我得到$path/file*,它成功展开了,&我得到了预期的3个文件。”@rici:所以OP对某些精神药物的含量非常高。@gniourf_gniourf:我不会走那么远:)它是可行的,只是它依赖于glob,而不匹配CWD中的任何内容(或在命令行中引用)。
$ cd -- "$(mktemp --directory)"
$ cat test.sh 
path="$1"
shift
cd "$path"
for file in $@
do
    echo "Found file: $file"
done
$ mkdir foo
$ touch foo/a foo/abc
$ sh test.sh foo a*
Found file: a
Found file: abc
#!/bin/bash

path=$1
shift
find_these=( "$@" )

for f in "${find_these[@]/#/$path/}" ; do
  echo "f is $f"
done