【问题标题】:Shebang line limit in bash and linux kernelbash 和 linux 内核中的 Shebang 行限制
【发布时间】:2012-06-04 12:37:32
【问题描述】:

我正在尝试执行由 zc.buildout 自动生成的 python 脚本,因此我无法控制它们。我的问题是 shebang 行 (#!) 对于 bash(80 个字符限制)或直接执行(一些我不知道的 Linux 内核常量)来说太长了。

这是一个示例脚本,可帮助您重现我的问题:

#!/././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././././bin/bash
echo Hola!

如何将 bash 或内核配置为允许更大的 shebang 行?

【问题讨论】:

  • 如果将脚本作为参数传递给解释器(bash x.sh 而不是./x.sh),shebang 行将作为注释被忽略,不会影响执行。
  • 我知道,问题是我也不是调用这些脚本的人...

标签: linux bash shebang


【解决方案1】:

由于内核编译时缓冲区限制,在 99.9% 的系统上限制为 127 个字符。

它在内核中被BINPRM_BUF_SIZE 限制,在include/linux/binfmts.h 中设置。

【讨论】:

  • 另见man execve:“#! 可执行 shell 脚本的第一行允许的最大行长度为 127 个字符。”
【解决方案2】:

如果您不想重新编译内核以获得更长的 shebang 行,您可以编写一个包装器:

#!/bin/bash

if [[ $# -eq 0 ]]; then
    echo "usage: ${0##*/} script [args ...]"
    exit
fi

# we're going to expand a variable *unquoted* to use word splitting, but
# we don't want to have path expansion effects, so turn that off
set -f

shebang=$(head -1 "$1")
if [[ $shebang == '#!'* ]]; then
    interp=( ${shebang#\#!} )        # use an array in case a argument is there too
else
    interp=( /bin/sh )
fi

# now run it
exec "${interp[@]}" "$@"

然后像这样运行脚本:wrapper.sh script.sh

【讨论】:

  • +1 解决所有问题的简单解决方法,无需任何内核更改、补丁或其他 hack。
【解决方案3】:

更新了@glenn jackman 的脚本以支持传入命令行参数。

顺便说一句,我在非常深的目录层次结构中创建 python virtualenv 时遇到了这个问题。

在我的例子中,这是一个在 Mesos 框架目录中创建的 virtualenv。

超长的 shebang 导致调用 xxx/.../venv/bin/pip 无用。

包装脚本被证明是最有用的。

#!/usr/bin/env bash

script="$1" 
shebang=$(head -1 "$script")

# use an array in case a argument is there too
interp=( ${shebang#\#!} )        

# now run it, passing in the remaining command line arguments
shift 1
exec "${interp[@]}" "$script" "${@}"

【讨论】:

  • 你能详细说明你是如何在虚拟环境中使用这个脚本的吗?我们的构建在虚拟环境的初始创建过程中失败,因为 #! easy_install 的路径已经太长了。
猜你喜欢
  • 1970-01-01
  • 2011-11-08
  • 2012-07-23
  • 2011-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多