Ubuntu – Test if operating from live session or not inside a shell script

live-cdlive-usbscriptssystem-installation

I have a shell script that can only be run from a live session (LiveCD or Live USB) because it shrinks the root filesystem of an actual installation, which can only be done when the filesystem is not mounted.

If the script is run from the live session, it should pursue its execution. If not, it should fail.

I cannot find a way to differentiate the live session and a "normal" user session, as the live session has a look-and-feel very close to the installed system sessions. The only thing I can tell so far is that live sessions always have ubuntu as the hostname, but I cannot rely on that since the user can choose this when installing Ubuntu.

Is there a way of identifying this in a shell script / command line?

(I hesitated between posting on Ask Ubuntu or Stack Overflow, I can delete the post and re-post on Stack Overflow if more appropriate)

Best Answer

No, the name is arbitrary, you can't assume anything based on that. However, the Live session does have a few quirks such as:

$df -h | grep -w /
/cow        2.0G   42M   1.9G  3% /

As you can see, the special device /cow is mounted on /. I'm not sure how portable this is, I doubt it will be the same for non Ubuntu Linuxes and it may also change in future releases but as long as it's not an actual device in /dev you can test for this very easily:

df | grep -w / | grep -q 'cow' && echo "Live session" || echo "Normal install"

Explanation:

  • df : print mounted file systems
  • grep -w / : print only the line that shows what is mounted on /. The -w option matches whole words only so that only / and not for example /home will be printed.
  • grep -q cow : The -q suppresses output, grep will exit with status >0 (error)if cow was not found and 0 (correct) if it was.
  • && echo "Live session" : PrintLive sessionif thegrep` was succesful
  • || echo "Normal install" : Else, print Normal install.

EDIT BY THE OP

In the end, here is the solution I implemented in my script, if it's somewhat useful:

#!/bin/bash

if [ ! $(df | grep -w / | grep -q '/cow') ]; then
  printf "This script must be run from a live session.\n"
  exit 1
fi