0

I am trying to restart the gui with the following bash script (under Mint + Cinnamon):

if ! type gnome-shell > /dev/null; then
    gnome-shell --replace
elif ! type cinnamon > /dev/null; then
    cinnamon --replace
fi

I got an error message, that the gnome-shell does not exist. Is there a way to write this script multi-platform?

inf3rno
  • 24,976
  • 11
  • 115
  • 197

1 Answers1

1

What you actually want is

type gnome-shell &> /dev/null

The &> redirects both stdout and stderr (bash only). You just redirected stdout, therefore you still get error messages. You're only interested in the return value of type, not the output.

Also, what is the negation doing there? You call gnome-shell if it does NOT exist? In case you checked the return value $?, remember 0 is true, 1 is false in shells:

type gnome-shell
echo $?   # prints '0', indicating success / true, or '1' if gnome-shell does not exist

The return value, or rather exit code / exit status, ($?) is what is evaluated by the if statement.

A little bit nicer:

function cmdExists()
{
  type "$1" &> /dev/null
}

function echoErr()
{
  echo "$1" 1>&2
}

if cmdExists gnome-shell; then
  gnome-shell --replace
elif cmdExists cinnamon; then
  cinnamon --replace
else
  echoErr 'No shell found'
  exit
fi

Some more useful thoughts on related topics:

EDIT: exit codes

Actually, every value except 0 is false in the shell. That is because programs use these values to indicate different errors.

There are also some exceptions. Inside (( )) you can use "normal" arithmetic... Shell arithmetic

Community
  • 1
  • 1
Daniel S
  • 456
  • 4
  • 17