击:如何在其他功能

问题描述:

我有这些功能在我的.bashrc中使用的功能(这是一个字符串PARAM):击:如何在其他功能

# 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 "[email protected]" & 
} 

测试NN功能之前,我创建了一个焦油

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,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 '"[email protected]"' bash "[email protected]" 
    fi 

    nohup nice -n 15 "[email protected]" & 
} 

这条线应该有自己的解释:

set -- bash -c '"[email protected]"' bash "[email protected]" 
  1. set --更改当前函数的参数;它用一组新值替换"[email protected]"
  2. bash -c '"[email protected]"'是显式的子shell调用。
  3. bash "[email protected]"是子外壳的参数。 bash$0(未使用)。外部现有参数"[email protected]"被传递给新的bash实例,如$1,$2等。这就是我们如何获得子shell来执行函数调用。

让我们看看如果您拨打nn untar test.txt.tar会发生什么情况。 type -t检查看到untar是一个函数。该功能已导出。然后setnn的参数从untar test.txt.tar更改为bash -c '"[email protected]"' bash untar test.txt.tar