1

我的 .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
4

1 回答 1

2

函数不是一等公民。shell 知道它们是什么,但其他命令,如find,xargsnice不知道。要从另一个程序调用函数,您需要 (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 "$@"
  1. set --改变当前函数的参数;它替换"$@"为一组新值。
  2. bash -c '"$@"'是显式的子shell 调用。
  3. bash "$@"是子shell的参数。bash$0(未使用)。外部现有参数以、等"$@"形式传递给新的 bash 实例。这就是我们让子 shell 执行函数调用的方式。$1$2

让我们看看如果你调用nn untar test.txt.tar. type -t检查看到untar是一个函数。函数被导出。然后setnn的参数从更改untar test.txt.tarbash -c '"$@"' bash untar test.txt.tar

于 2017-09-25T18:46:18.897 回答