linux - 狂欢 : how to use a function (which is a string param) in an other function

标签 linux bash ubuntu nohup nice

我的 .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 知道它们是什么,但其他命令如 findxargsnice 则不知道。要从另一个程序调用函数,您需要 (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(未使用)。外部现有参数 "$@" 作为 $1$2 等传递给新的 bash 实例。这就是我们获取子 shell 的方式执行函数调用。

让我们看看如果您调用 nn untar test.txt.tar 会发生什么。 type -t 检查发现 untar 是一个函数。函数被导出。然后 setnn 的参数从 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/

相关文章:

python - 在传入设置时使用 shell 脚本运行自定义 django manage.py 命令

python - 使 python 库可用于 rqworker

ubuntu - Ubuntu 上的 Webstorm : npm install issues and permissions on folders

python - 你如何在已经创建的 virtualenv 中设置你的 pythonpath?

linux - Git - Windows 和 linux 行尾

python - 文件作为 python netaddr 中的输入

linux - 找不到 bash 脚本命令

linux - 库和包含路径,~/lib 和 ~/include?

linux - 如何编辑 .gitignore 文件

linux - 在 BASH 参数扩展中用代字号 "~"替换子字符串时的行为不一致