Edit:
This assumes that you have installed the version first, with e.g.:
sudo apt install gcc-4.9 g++-4.9
Original:
And here is a one-liner for those who are lazy, just change change the number at the end to the version you want. It will make the change for gcc and/or g++
ls -la /usr/bin/ | grep -oP "[\S]*(gcc|g\+\+)(-[a-z]+)*[\s]" | xargs bash -c 'for link in ${@:1}; do sudo ln -s -f "/usr/bin/${link}-${0}" "/usr/bin/${link}"; done' 4.9
In this example I switched to 4.9
There are no error checks and what not in this example, so you might want to check what will be run before you run it. Just add echo before sudo. For completeness I provide check line as well:
ls -la /usr/bin/ | grep -oP "[\S]*(gcc|g\+\+)(-[a-z]+)*[\s]" | xargs bash -c 'for link in ${@:1}; do echo sudo ln -s -f "/usr/bin/${link}-${0}" "/usr/bin/${link}"; done' 4.9
The output from the check should be something like:
sudo ln -s -f /usr/bin/g++-4.9 /usr/bin/g++
sudo ln -s -f /usr/bin/gcc-4.9 /usr/bin/gcc
sudo ln -s -f /usr/bin/gcc-ar-4.9 /usr/bin/gcc-ar
sudo ln -s -f /usr/bin/gcc-nm-4.9 /usr/bin/gcc-nm
sudo ln -s -f /usr/bin/gcc-ranlib-4.9 /usr/bin/gcc-ranlib
sudo ln -s -f /usr/bin/x86_64-linux-gnu-g++-4.9 /usr/bin/x86_64-linux-gnu-g++
sudo ln -s -f /usr/bin/x86_64-linux-gnu-gcc-4.9 /usr/bin/x86_64-linux-gnu-gcc
sudo ln -s -f /usr/bin/x86_64-linux-gnu-gcc-ar-4.9 /usr/bin/x86_64-linux-gnu-gcc-ar
sudo ln -s -f /usr/bin/x86_64-linux-gnu-gcc-nm-4.9 /usr/bin/x86_64-linux-gnu-gcc-nm
sudo ln -s -f /usr/bin/x86_64-linux-gnu-gcc-ranlib-4.9 /usr/bin/x86_64-linux-gnu-gcc-ranlib
You can check the version after with:
gcc --version
Semi-detailed explanation:
- ls -la /usr/bin/ lists all files in /usr/bin
- | pipe (send) the output to the next command
- grep -oP matches the search regex per line. o only shows the result not the entire matched line. P tells grep to use perl-regex. I will not go into regex here, read up on it if you want to.
- xargs simply put, it gathers the results that are piped to it and send all of them to the end. i.e. to the command following xargs
- bash well, it's bash. The c flag tells it to use the string as a command. In this example it loops over the arguments sent from xargs by skipping the first (0th) argument, in this case the loop skips 4.9. The 0th argument is used in the loop to change the link.
- ln -s -f The s flag makes a symbolic link, f forces unlinking first if needed.