Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there for the bash something like perls __DATA__?

Tags:

bash

shell

Is there for the bash something like perls __DATA__? I mean the feature, that the code after __DATA__ will not be executed.

like image 860
sid_com Avatar asked Aug 13 '10 13:08

sid_com


2 Answers

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
like image 70
bcat Avatar answered Oct 05 '22 19:10

bcat


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?

like image 21
ennuikiller Avatar answered Oct 05 '22 19:10

ennuikiller