0

I have a variable(which is a string) which can have two values: (1)variable = null (2)variable = "some string value"

Now I have to apply a condition like:

if (variable is equal to null) then execute step 1 else execute step 2.

This script will be run in jenkins and actual value of variable will be replaced in the script in jenkins.

but my variable has just two values either null or some string "value"...but when script runs it replaces the values so when variable gets replaced it treats null also as a string..and so when i use -n it executes only the if part.....eg...if[-n variable -ge 1]..so when script runs...it gets replaced like this..[if -n null -ge 1] and it return true..which it shouldn't ..how to solve this

How do we check it in shell script?

0

1 Answer 1

1

Make use of unix test to check whether a string is empty or not.

 [ -z $var ] && echo empty || echo non empty # -z returns true on empty string
 [ -n $var ] && echo non empty || echo empty # -n returns true on non empty string.

Find mode details about test command on link or any other better site. Hope this helps.

6
  • Correct but for OP an if-statement would be easier to read and implement. Also you can suggest man test.
    – Walter A
    Commented Jun 23, 2017 at 20:24
  • but my variable has just two values either null or some string "value"...but when script runs it replaces the values so when variable gets replaced it treats null also as a string..and so when i use -n it executes only the if part.....eg...if[-n variable -ge 1]..so when script runs...it gets replaced like this..[if -n null -ge 1] and it return true..which it shouldnt ..how to solve this Commented Jun 26, 2017 at 9:29
  • There are some classic way to do check for empty string ( there are other better ways though ). Use [ "X${var}" = "X" ] && echo var is empty
    – Fidel
    Commented Jun 26, 2017 at 12:04
  • @WalterA, thanks for the comments. Will try to make more readable and added resources on my next opportunities
    – Fidel
    Commented Jun 26, 2017 at 12:05
  • On AIX my ksh script had an error when testing an empty var, better is [ -z "$var" ]. I am wondering what is easiest for others: your notation, writing with the keyword if or testing verbose with test -z "${var}"&& ....
    – Walter A
    Commented Jun 26, 2017 at 20:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.