bashsyntax-errorcasemd5sum

`line 1: syntax error near unexpected token `newline'` when run bash `case` function


#!/bin/bash
set -e

deb_folder='/home'


myinstall(){
    deb=$1
    temp="${1%.*}"
    num="${temp##*.}"
    temp2="${temp%.*}"
    method="${temp2##*.}"
    case "$method" in
    md5)
    md5=md5sum $deb
    echo 'here'
    if [[ "${md5:0:3}${md5: -3}" == "$num" ]]; then echo 'correct' else echo $deb'md5 error';false;fi
    ;;
    256)
    sha256=sha256sum $deb
    if [[ "${sha256:0:3}${sha256: -3}" == "$num" ]]; then apt-get install $deb; else echo $deb'sha256 error';false;fi
       ;;
    *) echo $deb'sum type wrong'
       ;;
esac
}

myinstall "${deb_folder}/rstudio-1.4.1106-amd64.md5.e596d3.deb"

Expect result of above bash script is correct or /home/rstudio-1.4.1106-amd64.md5.e596d3.debmd5 error,but I got here after change md5=md5sum $deb to md5=$(md5sum $deb).

Where is the problem?


Solution

  • Problem 1

    Instead of md5=md5sum $deb you probably meant md5=$(md5sum $deb) or even better md5=$(md5sum "$deb"). The same goes for sha256=sha256sum $deb.

    md5=$(md5sum $deb) runs the command md5sum $deb and stores its output in the variable md5.

    md5=md5sum $deb runs the "command" $deb while setting the environment variable md5=md5sum for this command. You may have seen this construct in idioms like IFS= read -r line or LC_ALL=C sort before.

    Problem 2

    The following if has only one branch. That else is very misleading.

    if [[ "${md5:0:3}${md5: -3}" == "$num" ]]; then echo 'correct' else echo $deb'md5 error';false;fi
    

    If written properly formatted, the problem becomes clear:

    if [[ "${md5:0:3}${md5: -3}" == "$num" ]]; then
      echo 'correct' else echo $deb'md5 error'
      false
    fi
    

    Here the else is not a keyword, but a simple argument to echo. If you enter the if you would get the output correct else echo /home/rstudio-1.4.1106-amd64.md5.e596d3.debmd5 error.

    To fix this, add a ; or linebreak before else.

    You may as well fix the check "${md5:0:3}${md5: -3}" == "$num". I don't think these things will ever be equal. Execute your script with set -x to print the values of your variables, then you see the problems.