0

I'm writing a script to customize a clean installation of Linux and there are several sections where it runs apt-get install. I've encountered some issues with my connection where it will occasionally stop working which can cause apt-get to fail and when this happens the script would continue to process the other commands.

The following script works, except now I'm hitting another issue: if the function is issued as aptinstall firefox firefox-locale-en for example, it only installs the first package that's listed.

I modified the script so that apt-get is run within a function that will retry if it fails up to 5 times:

# Install package - will retry download if connection fails up to 5 times and abort if unsuccessful
function aptinstall (){
local __pkg=$1
    set +x
    n=0
    until [ $n -ge 5 ]
    do
        apt-get install -y $__pkg && break
        n=$[$n+1]
        sleep 15 # Wait 15 seconds before trying to download and install packages again
    done
    if [ "$n" -eq 5 ]; then
        echo >&2 "An error has occurred. Please check your network connection."
        exit 1
    fi

Can anyone help me figure out why only the first package is installed? Thanks!

  • for __pkg do – Scott Oct 14 '17 at 21:38
  • 1
    Replacing do with for __pkg do results in install.sh: line 39: syntax error near unexpected token `}' where the end of the function is. I must be missing something but I'm not sure what it is, my bash scripting skills have gotten pretty rusty. – user255641 Oct 14 '17 at 22:12
1

Instead of using $1 use "$@".

You don't need the local variable __pkg. In my opinion it unnecessarily complicates the script.

Also I noticed that you're using $[expression] for arithmetic evaluation. That syntax is deprecated. I would recommend using $((expression)) instead. For example, n=$((n+1)).

This is beyond the scope of your question, but if you are having problems with apt-get timing out, you may want to look into solutions to avoid that, such as setting up a local mirror.

  • Perfect! Thanks for this, it works great. – user255641 Oct 14 '17 at 22:24
  • Or more compact, but not POSIX: until (( ++n > 5 )); do __try__; done; if (( n > 5 )); then __error__; fi – dave_thompson_085 Oct 15 '17 at 2:35

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy