Ian*_*ung 60 bash command-line xargs
我正在尝试运行以下命令:
find . -iname '.#*' -print0 | xargs -0 -L 1 foobar
Run Code Online (Sandbox Code Playgroud)
其中"foobar"是我的.bashrc文件中定义的别名或函数(在我的例子中,它是一个带有一个参数的函数).显然xargs不会将这些视为可以运行的东西.有没有一种聪明的方法可以解决这个问题?
eph*_*ent 37
由于只有你的交互式shell知道别名,为什么不直接运行别名xargs呢?
find . -iname '.#*' -print0 | while read -r -d '' i; do foobar "$i"; done
Run Code Online (Sandbox Code Playgroud)
如果您确定您的文件名中没有换行符(ick,为什么会这样?),您可以将其简化为
find . -iname '.#*' -print | while read -r i; do foobar "$i"; done
Run Code Online (Sandbox Code Playgroud)
或者甚至只是find -iname '.#*' | ...,因为默认目录是.,默认操作是-print.
还有一个选择:
IFS=$'\n'; for i in `find -iname '.#*'`; do foobar "$i"; done
Run Code Online (Sandbox Code Playgroud)
告诉Bash,单词只在换行符上分割(默认值:) IFS=$' \t\n'.不过,你应该小心这一点; 有些脚本无法很好地应对变化$IFS.
小智 12
使用Bash,您还可以指定传递给别名(或函数)的args数量,如下所示:
alias myFuncOrAlias='echo' # alias defined in your ~/.bashrc, ~/.profile, ...
echo arg1 arg2 | xargs -n 1 bash -cil 'myFuncOrAlias "$1"' arg0
echo arg1 arg2 | xargs bash -cil 'myFuncOrAlias "$@"' arg0
Run Code Online (Sandbox Code Playgroud)
小智 6
向被别名化的命令添加尾随空格会导致其他别名化命令扩展:
alias xargs='xargs ' # aliased commands passed to xargs will be expanded
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅此答案:https :
//stackoverflow.com/a/59842439/11873710
这不起作用,因为xargs期望能够作为其参数给出exec的程序.
因为foobar在你的情况下只是一个bash别名或函数,所以没有程序可以执行.
虽然它涉及bash为每个返回的文件启动find,但您可以编写一个小的shell脚本:
#!/bin/bash
. $(HOME)/.bashrc
func $*
Run Code Online (Sandbox Code Playgroud)
然后将该脚本的名称作为参数传递给 xargs