2012-03-25 92 views
2

我有一个脚本的第一行内容的字符串的名称,如庆典:找到解释

#!/bin/bash

,但它可以是任何东西,如

#!/path/to/another/interpret -some args -another arg

哪有我通过省略路径和参数来提取解释器的名称 - “bash”,“解释”?

我虽然关于找到第一个空白区分路径的参数。

你能帮忙吗?

+0

你说的 '提取' 是什么意思?你在哪里以及如何获得这些信息?脚本里面? – Bernhard 2012-03-25 09:54:52

+0

你确定一个shebang中的路径可以包含空白吗? – user123444555621 2012-03-25 09:55:04

+0

它不像我“知道如何去做”,但是,你可以做的是使用〜some〜命令将“/”字符串作为分隔符分隔开,并使用结果字符串数组的最后一个值...我猜测sed或awk或grep(和正则表达式)可以帮助你。例如grep -Po“/ [a-z,A-Z] {0-30} $”可以工作,但我不确定。基本上应该匹配“/ bash”,“/ sh”,但不是“/ some”。希望这个〜kinna〜有帮助 – 2012-03-25 09:58:14

回答

2

我不认为你可以在shebang中使用空格。如果你不能,你可以找到解释名字是这样的:

interpreter=`cat test.sh | head -n 1 | cut -d' ' -f 1` 
basename $interpreter 

编辑: 缩短版本:

interpreter=$(basename $(sed '2q;s/^#!//;s/ .*//' test.sh)) 
+1

可以直接使用'head -n 1 test.sh' – okm 2012-03-25 10:18:07

+0

ye,比上面更简单的版本: 'interpreter = basename \'head -n 1 test.sh \'' – wisent 2012-03-25 10:26:43

+0

你确实需要在'#!' - '#之后留出空格!/bin/sh'工作得很好。 – 2012-03-25 11:58:47

0
$ basename '#!/path/to/another/interpret -some args -another arg'|awk '{ print $1}' 
interpret 
0
set -- $(head -1 scriptname) 
case $1 in 
    "#!") 
    # whitespace after the #!, the interpreter is the 2nd word 
    interp=$2 
    ;; 
    "#!"*) 
    # no whitespace, strip the first 2 chars from the 1st word 
    interp=${1#??} 
    ;; 
    *) 
    echo no shebang at all 
    exit 
    ;; 
esac 
interp=$(basename "$interp")