How to judge whether a variable is empty in shell?

Source: Internet
Author: User
To determine whether the variables in a script are empty, I wrote a shell script like this:

  1. #! /Bin/sh
  2. # Filename: Test. Sh
  3. Para1 =
  4. If [! -N $ para1]; then
  5. Echo "is null"
  6. Else
  7. Echo "not null"
  8. Fi

Then run the Script: test. sh uses chmod + X to change the script that can be executed. After execution, the output result is not null, which is very strange. Finally, it is found by querying some data, you can determine whether a shell variable is null by using the following method:

1. variables are enclosed by quotation marks.

The result is null.

  1. #! /Bin/sh
  2. Para1 =
  3. If [! -N "$ para1"]; then
  4. Echo "is null"
  5. Else
  6. Echo "not null"
  7. Fi

2. Directly determine through Variables

The result is: Is null.

  1. #! /Bin/sh
  2. Para1 =
  3. If [! $ Para1]; then
  4. Echo "is null"
  5. Else
  6. Echo "not null"
  7. Fi

3. Use test to determine

The result is: dmin is not set!

  1. #! /Bin/sh
  2. Dmin =
  3. If test-z "$ dmin"
  4. Then
  5. Echo "dmin is not set! "
  6. Else
  7. Echo "dmin is set! "
  8. Fi

 

4. Use "" to judge

  1. #! /Bin/sh
  2. Dmin =
  3. If ["$ dmin" = ""]
  4. Then
  5. Echo "dmin is not set! "
  6. Else
  7. Echo "dmin is set! "
  8. Fi

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.