我的 .bashrc 中有这些函数:
# This function just untar a file:
untar()
{
tar xvf $1
}
# This function execute a command with nohup (you can leave the terminal) and nice for a low priority on the cpu:
nn()
{
nohup nice -n 15 "$@" &
}
在测试 nn 函数之前,我创建了一个 tar:
echo test > test.txt
tar cvf test.txt.tar test.txt
现在我要做的是:
nn untar test.txt.tar
但只有这个有效:
nn tar xvf test.txt.tar
这里是nohup.out中的错误:
nice: ‘untar’: No such file or directory
最佳答案
函数不是一等公民。 shell 知道它们是什么,但其他命令如 find
、xargs
和 nice
则不知道。要从另一个程序调用函数,您需要 (a) 将其导出到子 shell,以及 (b) 显式调用子 shell。
export -f untar
nn bash -c 'untar test.txt.tar'
如果你想让调用者更容易,你可以自动执行此操作:
nn() {
if [[ $(type -t "$1") == function ]]; then
export -f "$1"
set -- bash -c '"$@"' bash "$@"
fi
nohup nice -n 15 "$@" &
}
这一行值得解释:
set -- bash -c '"$@"' bash "$@"
set --
改变当前函数的参数;它将"$@"
替换为一组新值。bash -c '"$@"'
是显式子 shell 调用。bash "$@"
是子 shell 的参数。bash
是$0
(未使用)。外部现有参数"$@"
作为$1
、$2
等传递给新的 bash 实例。这就是我们获取子 shell 的方式执行函数调用。
让我们看看如果您调用 nn untar test.txt.tar
会发生什么。 type -t
检查发现 untar
是一个函数。函数被导出。然后 set
将 nn
的参数从 untar test.txt.tar
更改为 bash -c '"$@"' bash untar测试.txt.tar
.
关于linux - 狂欢 : how to use a function (which is a string param) in an other function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46412011/