开发者

Is there for the bash something like perls __DATA__?

Is there开发者_开发百科 for the bash something like perls __DATA__? I mean the feature, that the code after __DATA__ will not be executed.


Shell scripts are parsed on a line-by-line basis as they execute, so you just need to ensure execution never reaches the data you want to protect. You could do this, for instance:

# Some shell code...

exit

[data (possibly binary) goes here]

To actually read this data from your script, you can use some sed magic to extract everything after the first line containing only __DATA__, then store the output of that sed in a variable. Here's an example:

#!/bin/sh

data=$(sed '0,/^__DATA__$/d' "$0")
printf '%s\n' "$data"

exit

__DATA__
FOO BAR BAZ
LLAMA DUCK COW

If you save this script as test-data.sh and make it executable, you can run it and get the following output:

$ ./test-data.sh
FOO BAR BAZ
LLAMA DUCK COW


First of all perl's "__DATA__" pragma is a way of supplying input to $_ without specifying a file. There is no equivalent in bash since it has nothing similar to $_. However you can supply data directly in a bash script by other means such as explicit setting variables, using HERE docs etc.

However I'm not convinced this is what you wish to do. It seems your after some sort of block commenting method. Is that the case?


This is a useful technique if you want to provide usage info for your script, but do not want to clutter up the main line of code with the help text. It's also great if you want to reference the usage more than once. To wit, a snippet from a shell script of mine:

...
declare OPTSARGS    
OPTSARGS=$(getoptp -o wh --long nopager,help -n myScript-- "$@")
status=$? 
if ((status != 0))    
then
    printf '%s\n' "$(sed '0,/^__USAGE__$/d' $0)"
    exit $status
fi
eval set -- "$OPTSARGS"  
while true
do
    case "$1" in
        -w) diffargs="$diffargs -w"; shift;;
        --nopager) pager=cat; shift;;
        --) shift; break ;; ## end of opts, remaining $*, if any, are args
        -h | --help)
            printf '%s\n' "$(sed '0,/^__USAGE__$/d' $0)"
            exit 0;;
        *)
            echo "Internal error!"
            printf '%s\n' "$(sed '0,/^__USAGE__$/d' $0)"
            exit 1;;
   esac
done

...

echo "Done"
exit 0

__USAGE__
myScript [-w] [--nopager] [file [file...] ]

Some description goes here.

       -w - Do not compare whitespace
--nopager - Do not pass the output through 'less'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜