2

I'm trying to understand a script that will stop when executed as root:

#!/usr/bin/env bash

if [ x"$(whoami)" = x"root" ]; then
    echo "Error: don't run this script as root"
    exit 1
fi

I have tested this and it works as intended even if I remove the x in the if statement. My question is why is the x in x"$(whoami)" and x"root" needed?

builder-7000
  • 7,131
  • 3
  • 19
  • 43

1 Answers1

1

basically the [ is a softlink to an external program called test, therefore the condition is passed to it as program arguments, and doing so if you don't surround a $variable with "$quotes" , and the variable happens to be empty it won't be considered as an empty argument, it will be considered as no argument (nothing)

#!/bin/bash -eu

var=bla

if [[ $var == bla ]];then
  echo first test ok
fi

var=""

if [[ $var == "" ]];then
  echo second test ok
fi

if [ "$var" == "" ];then
  echo third test ok
fi

if [ x$var == "x" ];then
  echo fourth test ok
fi

echo this will fail:

if [ $var == "" ];then
  echo fifth test ok
fi

echo because it is the same as writing:

if [ == "" ];then
  echo sixth test is obviously eroneous
fi

echo but also you should quote your variables because this will work:

var="a b"

if [ "$var" == "a b" ];then
  echo seventh test ok
fi

echo ... but this one won\'t as test now has four arguments:
if [ $var == "a b" ];then
  echo eighth test ok
fi
Imre
  • 322
  • 3
  • 8
  • 1
    In Bash, `[` is a built-in, not an external program. – Benjamin W. Nov 25 '18 at 22:15
  • 1
    agree about `[`, but otherwise a excellent early post. Your showing all to possibilities is an excellent example of "code explained by illustrations" (IMHO), Keep posting! Good luck to all. – shellter Nov 26 '18 at 04:51