Running a .sh to execute multiple commands

Solution 1:

Simple really - you need to separate the commands. For instance this:

#!/bin/bash
sudo apt-get update
sudo apt-get upgrade

will update the package lists, and then the packages. Another possibility is this (probably better, as the && will only allow the upgrade command to run if the update exits successfully):

#!/bin/bash
sudo apt-get update && sudo apt-get upgrade

This should run the commands for updating the list of packages and then the package themselves. This would need to be saved into a text file (e.g. updatescript in the home directory). You can then make it executable by running:

 chmod +x ./updatescript

or by right clicking on the file and making it executable in its properties:

and run it with this in terminal:

 ./updatescript

Note(s):

There is an option (-y) available that can be used with the upgrade command so it does not prompt before upgrading the packages. It is a good idea to check what apt-get is doing before it upgrades the packages, as it may/will do something stupid or something you don't want it do. More info on options like this can be found by running man apt-get.

This also means it is more ideal to use the terminal to run the script, as you can check what it is updating, and then run it. If you want a GUI way to run the updates, use the software-center as that it is what it is for.

Solution 2:

Just to add a few points to the excellent answer by @Wilf,

you can run commands in paralell if you want for any reason, for example, an autostart script for OpenBox might look like this:

#!/bin/bash

nitrogen --restore &
tint2 &
tilda

This will set a background image using nitrogen, start the panel tint2 and start the Quake3-style dropdown console tilda, all at the same time. This is useful if you don't need a program to finish before you launch the next one. Not the case for apt-get update and apt-get upgrade though!

Notice the & sign at the end of each line. This will cause the shell to fork that process into the background and continue execution. Note how it's different from &&, which is basically an and sign, command_1 && command_2 will executecommand_1 and if it exits with success, only then run command_2, while command_1 & command_2 will start the second right after the first.


Also, you could just stack commands to have them executed serially, like so:

#!/bin/bash

apt-get update
apt-get upgrade

This will run apt-get upgrade after apt-get update is finished, but regardless of the result. So even if, for example, the update quits with a network error, the upgrade will still be run.

You can also do this in one line, using the ; sign: apt-get update ; apt-get upgrade. Again, this solution is not optimal for these particular commands, but it might come in handy in other situations.


One quick final point, you can also break lines containing && as such:

command_1 &&
command_2

This will be the same as command_1 && command_2.