Search code examples
linuxbashopensuseself-extracting

Bash - Self extracting script error


I am working on creating self extracting shell script on Open SuSE. I am referencing this link. My code is shown below -

#!/bin/bash
function die ()
            { echo "Error!"; 
                exit 1 ;
            }

echo Extracting...

# Script will need to find where is the archive. So search for "ARCHIVE" in this script and
# save the line number

archive=$(grep --text --line-number 'ARCHIVE:$' $0)

echo $archive

tail -n +$((archive + 1)) $0 | gzip -vdc - | tar -xvf - > /dev/null || die

echo Extraction completed

exit 0

ARCHIVE:

After I executed above script I got below output. Which I think is incorrect and causing error.

Extracting...
22:ARCHIVE:
./symhelp_self_extract.sh: line 16: 22:ARCHIVE:: syntax error in expression (error token is ":ARCHIVE:")

gzip: stdin: unexpected end of file
tar: This does not look like a tar archive
tar: Exiting with failure status due to previous errors
Error!

Can anyone will explain what syntax error is this?

Thanks,

Omky


Solution

  • If you need the line number:

    archive=$(grep --text --line-number 'ARCHIVE:$' "$0")
    archive=${archive%%:*}
    

    Or

    archive=$(awk '/ARCHIVE:$/{print NR; exit}' "$0")
    

    The cause of your problem was that you were trying to do arithmetic on something that's not a number:

    $((archive + 1))  ## here $archive = 22:ARCHIVE: before
    

    Always quote your variables as well:

    archive=$(grep --text --line-number 'ARCHIVE:$' "$0")
    ...
    tail -n "+$((archive + 1))" "$0"
    

    With awk you'd get a simpler approach:

    awk -v r='ARCHIVE:$' '!p && $0 ~ r { p = 1; getline } p' "$0" | gzip -vdc - | tar -xvf - > /dev/null || die