What means if [ "x/usr/bin" != "x" ] in bash script? [duplicate]

I'm trying to understand some sequence of bash scripts, and on one of the steps there is a condition:

if [ "x/usr/bin" != "x" ]; then <do some actions>

What do the following mean?

  • x in x/usr/bin
  • x in the right hand side of the testing equation?
2

1 Answer

It's a well known bashism.

If a variable (say $foo in this example) might be empty or might hold a value,

If foo="", then

 if [ "$foo" = "bar" ]

expands to

if [ = "bar" ]

a syntax error :-(

If one uses

if [ "x$foo" = "xbar" ] 

it expands to

if [ "x" = "xbar" ]

No syntax error.

There are better ways to check for empty variables, like

if [[ -n "$foo" ]]
6

You Might Also Like