1
#!/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?

kittygirl
  • 2,255
  • 5
  • 24
  • 52
  • 1
    Btw.: Please paste your script at [shellcheck.net](http://www.shellcheck.net/) and try to implement the recommendations made there. – Cyrus Jul 17 '21 at 08:41
  • Please don't change your question in ways that invalidate existing answers. Also, when you expected `correct`, you always would get a `here` first, because there is an `echo here` before your `if ...; then echo correct`. Please complete your expected output and actual output. – Socowi Jul 17 '21 at 08:52
  • @Socowi,after `here`,`if ...; then echo correct else` should output too.why not? – kittygirl Jul 17 '21 at 08:57

1 Answers1

1

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.

Socowi
  • 25,550
  • 3
  • 32
  • 54
  • Thanks,revised question as your answer.But output is `here`,expect output shoud be `correct` or `/home/rstudio-1.4.1106-amd64.md5.e596d3.debmd5 error` – kittygirl Jul 17 '21 at 08:52