Linux check if variable is set

How to check the variable is set or empty in bash

Syntax:

‘-v’ or ‘-z’ option is used to check the variable is set or unset. The above Boolean expression will return true if the variable is set and returns false if the variable is not set or empty.

Parameter substitute is another way to check the variable is set or unset. If the variable is set, then the value of the string will return otherwise null will return.

Example-1: Check the variable is set or unset using ‘-z’ option

Create a bash file named check_var1.sh with the following script. Here, the first `if` condition will return true and “Num variable is not set” will print. In the next statement, 20 is assigned to the variable, $Num. The second `if` condition will returns false and “Num is set and the value of Num=20” will print.

check_var1.sh

Example-2: Check the variable is set or unset using parameter substitute

Create a bash file named “check_var2.sh” and add the following script. Here, a string value is assigned to the variable, $str before checking the variable is set or unset. The ‘if’ condition will return true and the message, “’str’ variable is set and the value is Hello” will print.

check_var2.sh

Example-3: Check the variable is empty or not

Create a bash file named “check_var3.sh” and add the following script. The script will store the first command-line argument into a variable, $argv that is tested in the next statement. The output will be “First argument is empty” if no argument is passed otherwise the value of the first argument will be printed.

check_var3.sh

Run the script without any argument.

Run the script with an argument.

Conclusion

Different ways to check the variable is set or unset or empty are shown in this tutorial by using various examples. Hope, this tutorial will help the users to learn the ways of testing any bash variable.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

How to check if bash variable defined in script

I need to set a bash environment variable called PURGEIMAGE and take specific actions in my script. For example, if PURGEIMAGE set, then purge images from CDN else just URL. I am going to call my script as PURGEIMAGE=yes ./purgecache.sh url1 url2 . So how do I know if a bash variable set at the CLI and used in my bash script running on Linux or Unix-like systems?

We can pass the -z option to the if command or conditional expression to check if a bash variable defined in script or not.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Bash running on Linux or Unix
Est. reading time 2m

To find out if a bash variable is defined:

  1. Return true if a bash variable is unset or set to the empty string: if [ -z $ ];
  2. Also try: [ -z $ ] && echo «\$my_bash_var not defined»
  3. Determine if a bash variable is set or not : [[ ! -z $ ]] && echo «Set» || echo «Not defined»
  4. Return true if the variable is set on Bash version 4.2+ : [ -v $VAR ] && echo «Bash \$VAR NOT set»

if command syntax and example to see if bash variable named PURGEIMAGE set or not

The syntax is simple:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Then we run our script as
$ /path/to/script
$ PURGEIMAGE=whatever /path/to/script
# use the export command to export variable to sub-shells
$ export PURGEIMAGE=yes
$ /path/to/script
All exported variables can undefined values as follows using the unset command $ unset PURGEIMAGE
$ /path/to/script

How does $ syntax works?

Let us print commands and their arguments as script is executed by using the set command:

Another option to see if bash shell variable is set or not

We can try the control operators. The syntax is:

If portability is not your concern try [[ syntax

The following are bash specific option, and you need bash version 4.x+. I would avoid these examples due to portability issues if I were you, but I provide them below as they are in bash man pages.

Checking if a variable is set in Bash or not

The -v VAR returns true if the shell variable VAR is set:

Putting it all together

Summing up

CDN like Cloudfront and Cloudflare allows us to cache both images and HTML pages aggressively on the edge node. By caching those assets, we can speed up the website. However, when we updated pages, we need to remove URLs and images from the cache. However, often mages are not required to purge as we only update pages. This simple bash script allows me to purge assets as per our needs on-demand. See:

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Please explain how $is different than $? I thought you were trying to say if PURGEIMAGE was not defined is value would be set to foobar but that is not the case. Likewise, I am not seeing the difference in my test scripts if I remove +foobar?

Interesting, I like bash 4.2 solution. Very easy to use

Источник

How to check if an environment variable exists and get its value? [duplicate]

I am writing a shell script. In this shell script, I am have a variable that either takes a default value, or the value of an environment variable. However, the environment variable doesn’t have to be present.

For instance, assume, before running the script, I perform the following operation:

How do I tell the script to search for this environment variable, and store its value in a variable inside the script. Moreover, how do I tell the script that if this environment variable does not exist, store a default variable?

5 Answers 5

[ -z «$» ] checks whether DEPLOY_ENV has length equal to zero. So you could run:

If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

There’s also the $ form, which substitutes the default value only when parameter is unset (but not when it’s null).

To demonstrate the difference between the two:

If you don’t care about the difference between an unset variable or a variable with an empty value, you can use the default-value parameter expansion:

If you do care about the difference, drop the colon

You can also use the -v operator to explicitly test if a parameter is set.

There is no difference between environment variables and variables in a script. Environment variables are just defined earlier, outside the script, before the script is called. From the script’s point of view, a variable is a variable.

You can check if a variable is defined:

and then set a default value for undefined variables or do something else.

The -z checks for a zero-length (i.e. empty) string. See man bash and look for the CONDITIONAL EXPRESSIONS section.

You can also use set -u at the beginning of your script to make it fail once it encounters an undefined variable, if you want to avoid having an undefined variable breaking things in creative ways.

Источник

Bash Shell: Find Out If a Variable Is Set or Not

H ow do I check if a bash shell variable called $input is defined or not under BSD / Apple OS X / Unix / Linux like operating systems?

Method #1: Bash Variable Existence Check

The syntax is as follows to determine if $input is defined or not:

In this example your script will stop executing if the variable $input is not defined:

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

In this example, make sure $input is defined and is not empty, enter:

Here is an example that make sure $_php_map_extension is defined:

Method #2: isvarset() function

The above examples are useful for a sanity checking. Finally, you can use the following code:

Method 3: Using the Length of STRING

The -z option to test command returns TRUE of the Length of STRING is zero. You can use the following syntax:

The above syntax will tell if a variable is defined or not defined or defined with a empty value in a bash shell script.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

Hi vitek,
in method 3, last line there’s a typo:
\”$input\” instead of “\$input\”
Kind regards
lazarus

You have an easier way to check if a variable is set or not even if you enable -u (set -u = Treat unset variables as an error when substituting.)

[ “$” != “NOTDEF” ] && echo var is defined || echo var is not defined.

$Use Default Values. If parameter is unset or null, the expansion of word is
substituted. Otherwise, the value of parameter is substituted.

The bash parameter expansions (:-, :=, . :+) are very helpful.
See Parameter Expansion in the bash man page or read here:
http://tiswww.case.edu/php/chet/bash/bash.html#lbBB

But there is an additional option with Bash 4.2. The -v operator:

snippet:
test/[/[[ have a new -v variable unary operator, which returns success if `variable’ has been set.

Источник

Читайте также:  Курсор мыши стрелка windows
Оцените статью