【问题标题】:Bash : how to use a function (which is a string param) in an other functionBash:如何在另一个函数中使用一个函数(它是一个字符串参数)
【发布时间】:2018-03-06 19:47:44
【问题描述】:
我的 .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
【问题讨论】:
标签:
linux
bash
ubuntu
nohup
nice
【解决方案1】:
函数不是一等公民。 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 test.txt.tar。