tags:

views:

55

answers:

2

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

+4  A: 

Shell scripts are parsed on a line-by-line basis as they execute, so you just need to insure 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
bcat
+3  A: 

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?

ennuikiller
Yes, but the other part is interesting too. So I will accept the exit solution though it is not as nice as __DATA__ because after __DATA__ there is no more syntax-highlighting and __DATA__ itself is more visible in the code than exit. For supplying data I would probably us a HERE doc since it is easier to remember than bcat's proposal.
sid_com
Yes, using a heredoc is almost certainly the best solution for supplying large amounts of data to a script. The only time I'd use my solution (other than as a proof of concept) is if I needed the ability to easily include data in a shell script that could possibly include the heredoc terminator.
bcat