How-To Geek

How to work with variables in bash.

Want to take your Linux command-line skills to the next level? Here's everything you need to know to start working with variables.

Hannah Stryker / How-To Geek

Quick Links

Variables 101, examples of bash variables, how to use bash variables in scripts, how to use command line parameters in scripts, working with special variables, environment variables, how to export variables, how to quote variables, echo is your friend, key takeaways.

  • Variables are named symbols representing strings or numeric values. They are treated as their value when used in commands and expressions.
  • Variable names should be descriptive and cannot start with a number or contain spaces. They can start with an underscore and can have alphanumeric characters.
  • Variables can be used to store and reference values. The value of a variable can be changed, and it can be referenced by using the dollar sign $ before the variable name.

Variables are vital if you want to write scripts and understand what that code you're about to cut and paste from the web will do to your Linux computer. We'll get you started!

Variables are named symbols that represent either a string or numeric value. When you use them in commands and expressions, they are treated as if you had typed the value they hold instead of the name of the variable.

To create a variable, you just provide a name and value for it. Your variable names should be descriptive and remind you of the value they hold. A variable name cannot start with a number, nor can it contain spaces. It can, however, start with an underscore. Apart from that, you can use any mix of upper- and lowercase alphanumeric characters.

Here, we'll create five variables. The format is to type the name, the equals sign = , and the value. Note there isn't a space before or after the equals sign. Giving a variable a value is often referred to as assigning a value to the variable.

We'll create four string variables and one numeric variable,

my_name=Dave

my_boost=Linux

his_boost=Spinach

this_year=2019

Defining variables in Linux.

To see the value held in a variable, use the echo command. You must precede the variable name with a dollar sign $ whenever you reference the value it contains, as shown below:

echo $my_name

echo $my_boost

echo $this_year

Using echo to display the values held in variables in a terminal window

Let's use all of our variables at once:

echo "$my_boost is to $me as $his_boost is to $him (c) $this_year"

echo

The values of the variables replace their names. You can also change the values of variables. To assign a new value to the variable, my_boost , you just repeat what you did when you assigned its first value, like so:

my_boost=Tequila

my_boost=Tequila in a terminal window

If you re-run the previous command, you now get a different result:

echo

So, you can use the same command that references the same variables and get different results if you change the values held in the variables.

We'll talk about quoting variables later. For now, here are some things to remember:

  • A variable in single quotes ' is treated as a literal string, and not as a variable.
  • Variables in quotation marks " are treated as variables.
  • To get the value held in a variable, you have to provide the dollar sign $ .
  • A variable without the dollar sign $ only provides the name of the variable.

Correct an incorrect examples of referencing variables in a terminal window

You can also create a variable that takes its value from an existing variable or number of variables. The following command defines a new variable called drink_of_the_Year, and assigns it the combined values of the my_boost and this_year variables:

drink_of-the_Year="$my_boost $this_year"

echo drink_of_the-Year

drink_of-the_Year=

Scripts would be completely hamstrung without variables. Variables provide the flexibility that makes a script a general, rather than a specific, solution. To illustrate the difference, here's a script that counts the files in the /dev directory.

Type this into a text file, and then save it as fcnt.sh (for "file count"):

#!/bin/bashfolder_to_count=/devfile_count=$(ls $folder_to_count | wc -l)echo $file_count files in $folder_to_count

Before you can run the script, you have to make it executable, as shown below:

chmod +x fcnt.sh

chmod +x fcnt.sh in a terminal window

Type the following to run the script:

./fcnt.sh in a terminal window

This prints the number of files in the /dev directory. Here's how it works:

  • A variable called folder_to_count is defined, and it's set to hold the string "/dev."
  • Another variable, called file_count , is defined. This variable takes its value from a command substitution. This is the command phrase between the parentheses $( ) . Note there's a dollar sign $ before the first parenthesis. This construct $( ) evaluates the commands within the parentheses, and then returns their final value. In this example, that value is assigned to the file_count variable. As far as the file_count variable is concerned, it's passed a value to hold; it isn't concerned with how the value was obtained.
  • The command evaluated in the command substitution performs an ls file listing on the directory in the folder_to_count variable, which has been set to "/dev." So, the script executes the command "ls /dev."
  • The output from this command is piped into the wc command. The -l (line count) option causes wc to count the number of lines in the output from the ls command. As each file is listed on a separate line, this is the count of files and subdirectories in the "/dev" directory. This value is assigned to the file_count variable.
  • The final line uses echo to output the result.

But this only works for the "/dev" directory. How can we make the script work with any directory? All it takes is one small change.

Many commands, such as ls and wc , take command line parameters. These provide information to the command, so it knows what you want it to do. If you want ls to work on your home directory and also to show hidden files , you can use the following command, where the tilde ~ and the -a (all) option are command line parameters:

Our scripts can accept command line parameters. They're referenced as $1 for the first parameter, $2 as the second, and so on, up to $9 for the ninth parameter. (Actually, there's a $0 , as well, but that's reserved to always hold the script.)

You can reference command line parameters in a script just as you would regular variables. Let's modify our script, as shown below, and save it with the new name fcnt2.sh :

#!/bin/bashfolder_to_count=$1file_count=$(ls $folder_to_count | wc -l)echo $file_count files in $folder_to_count

This time, the folder_to_count variable is assigned the value of the first command line parameter, $1 .

The rest of the script works exactly as it did before. Rather than a specific solution, your script is now a general one. You can use it on any directory because it's not hardcoded to work only with "/dev."

Here's how you make the script executable:

chmod +x fcnt2.sh

chmod +x fcnt2.sh in a terminal window

Now, try it with a few directories. You can do "/dev" first to make sure you get the same result as before. Type the following:

./fnct2.sh /dev

./fnct2.sh /etc

./fnct2.sh /bin

./fnct2.sh /dev in a terminal window

You get the same result (207 files) as before for the "/dev" directory. This is encouraging, and you get directory-specific results for each of the other command line parameters.

To shorten the script, you could dispense with the variable, folder_to_count , altogether, and just reference $1 throughout, as follows:

#!/bin/bash file_count=$(ls $1 wc -l) echo $file_count files in $1

We mentioned $0 , which is always set to the filename of the script. This allows you to use the script to do things like print its name out correctly, even if it's renamed. This is useful in logging situations, in which you want to know the name of the process that added an entry.

The following are the other special preset variables:

  • $# : How many command line parameters were passed to the script.
  • $@ : All the command line parameters passed to the script.
  • $? : The exit status of the last process to run.
  • $$ : The Process ID (PID) of the current script.
  • $USER : The username of the user executing the script.
  • $HOSTNAME : The hostname of the computer running the script.
  • $SECONDS : The number of seconds the script has been running for.
  • $RANDOM : Returns a random number.
  • $LINENO : Returns the current line number of the script.

You want to see all of them in one script, don't you? You can! Save the following as a text file called, special.sh :

#!/bin/bashecho "There were $# command line parameters"echo "They are: $@"echo "Parameter 1 is: $1"echo "The script is called: $0"# any old process so that we can report on the exit statuspwdecho "pwd returned $?"echo "This script has Process ID $$"echo "The script was started by $USER"echo "It is running on $HOSTNAME"sleep 3echo "It has been running for $SECONDS seconds"echo "Random number: $RANDOM"echo "This is line number $LINENO of the script"

Type the following to make it executable:

chmod +x special.sh

fig13 in a terminal window

Now, you can run it with a bunch of different command line parameters, as shown below.

./special.sh alpha bravo charlie 56 2048 Thursday in a terminal window

Bash uses environment variables to define and record the properties of the environment it creates when it launches. These hold information Bash can readily access, such as your username, locale, the number of commands your history file can hold, your default editor, and lots more.

To see the active environment variables in your Bash session, use this command:

env | less in a terminal window

If you scroll through the list, you might find some that would be useful to reference in your scripts.

List of environment variables in less in a terminal window

When a script runs, it's in its own process, and the variables it uses cannot be seen outside of that process. If you want to share a variable with another script that your script launches, you have to export that variable. We'll show you how to this with two scripts.

First, save the following with the filename script_one.sh :

#!/bin/bashfirst_var=alphasecond_var=bravo# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"export first_varexport second_var./script_two.sh# check their values againecho "$0: first_var=$first_var, second_var=$second_var"

This creates two variables, first_var and second_var , and it assigns some values. It prints these to the terminal window, exports the variables, and calls script_two.sh . When script_two.sh terminates, and process flow returns to this script, it again prints the variables to the terminal window. Then, you can see if they changed.

The second script we'll use is script_two.sh . This is the script that script_one.sh calls. Type the following:

#!/bin/bash# check their valuesecho "$0: first_var=$first_var, second_var=$second_var"# set new valuesfirst_var=charliesecond_var=delta# check their values againecho "$0: first_var=$first_var, second_var=$second_var"

This second script prints the values of the two variables, assigns new values to them, and then prints them again.

To run these scripts, you have to type the following to make them executable:

chmod +x script_one.shchmod +x script_two.sh

chmod +x script_one.sh in a terminal window

And now, type the following to launch script_one.sh :

./script_one.sh

./script_one.sh in a terminal window

This is what the output tells us:

  • script_one.sh prints the values of the variables, which are alpha and bravo.
  • script_two.sh prints the values of the variables (alpha and bravo) as it received them.
  • script_two.sh changes them to charlie and delta.
  • script_one.sh prints the values of the variables, which are still alpha and bravo.

What happens in the second script, stays in the second script. It's like copies of the variables are sent to the second script, but they're discarded when that script exits. The original variables in the first script aren't altered by anything that happens to the copies of them in the second.

You might have noticed that when scripts reference variables, they're in quotation marks " . This allows variables to be referenced correctly, so their values are used when the line is executed in the script.

If the value you assign to a variable includes spaces, they must be in quotation marks when you assign them to the variable. This is because, by default, Bash uses a space as a delimiter.

Here's an example:

site_name=How-To Geek

site_name=How-To Geek in a terminal window

Bash sees the space before "Geek" as an indication that a new command is starting. It reports that there is no such command, and abandons the line. echo shows us that the site_name variable holds nothing — not even the "How-To" text.

Try that again with quotation marks around the value, as shown below:

site_name="How-To Geek"

site_name=

This time, it's recognized as a single value and assigned correctly to the site_name variable.

It can take some time to get used to command substitution, quoting variables, and remembering when to include the dollar sign.

Before you hit Enter and execute a line of Bash commands, try it with echo in front of it. This way, you can make sure what's going to happen is what you want. You can also catch any mistakes you might have made in the syntax.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Assign result of conditional expression to environment variable

I'd like to store the result of a conditional expression in an environment variable.

but the value of $C after running that is an empty string.

I could of course do something like this:

but I'm sure there's a better way of doing it.

  • environment-variables

user16768564's user avatar

  • 1 For the record, "true" and "false" there are no different from any other string such as "you" and "me". Also bash is not programming language like Java or so, therefore you expectation that it has builtin facility that automagically converts a boolean type value (which isn't exactly a thing in bash either) to a string was never real. –  Tom Yan Mar 15, 2022 at 16:09
  • Besides, $(command) expands the what command outputs to stdout, and [ 'A' == 'B' ] doesn't output anything anyway, so. –  Tom Yan Mar 15, 2022 at 16:15
  • @TomYan I'm aware that environment variables are strings. And I'm aware that [ 'A' == 'B' ] does not output anything which is why I asked the question. So to clarify, I'd like $C to be a string that is either 'true' or 'false' based on the result of the expression. –  user16768564 Mar 15, 2022 at 16:22

2 Answers 2

I believe the simplest solution is this:

This just negates the exit code of the test command and assigns it to $C .

  • you may as well edit your question and answer additionally by replacing the single quotes with double quotes; while neither of them are necessary in your showcase, most likely you would want something like [ "$X" = "$Y" ] at the end of the day, in which case single-quotes will change the meaning completely. –  Tom Yan Mar 15, 2022 at 19:24
  • @TomYan Good point. –  user16768564 Mar 15, 2022 at 21:07

Use an expression like this:

harrymc's user avatar

  • This results in an error: bash: 'A' == 'B' ? 1 : 0 : syntax error: operand expected (error token is "'A' == 'B' ? 1 : 0 ") . I think the string comparison is the problem because variable=$(( 1 == 1 ? 1 : 0 )) works. –  user16768564 Mar 15, 2022 at 16:37
  • Can't test here: try double-quotes. –  harrymc Mar 15, 2022 at 16:46
  • Double quotes work! Thanks! –  user16768564 Mar 15, 2022 at 16:48
  • I just noticed that now it always results in 1 (with variable=$(( "A" == "B" ? 1 : 0 )) ), no matter if the strings are equal or not. –  user16768564 Mar 15, 2022 at 17:07
  • You don't need any kind of quotes when there's nothing to expand or escape. As for why this doesn't work, it's because (( A == B )) is pretty much equivalent to (( 0 == 0 )) , for it's doing arithmetic: gnu.org/software/bash/manual/html_node/Shell-Arithmetic.html (which is probably also why only double quotes are expected / allowed, for parameter expansion). –  Tom Yan Mar 15, 2022 at 19:16

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged bash shell environment-variables ..

  • The Overflow Blog
  • Exploring the inclusive tech revolution sponsored post
  • Would you trust an AI bot to find the fix for vulnerabilities in your code?
  • Featured on Meta
  • Site maintenance - Saturday, February 24th, 2024, 14:00 - 22:00 UTC (9 AM - 5...
  • Upcoming privacy updates: removal of the Activity data section and Google...

Hot Network Questions

  • Confusion over Microfacet-based BRDFs and Normal Distribution Functions
  • Movie about a team of people drilling to the center of the Earth to save humanity
  • Applications of High School Geometry
  • LaTeX bad neighbours -- how to deal with it
  • Why are my new switches operating in reverse?
  • Instantly regretting transferring to new team
  • Reading the motto of Obispado de Cuenca
  • Why is post exposure vaccines given for some diseases & why does it work?
  • Were Mr. Darcy and Mr. Bennet formally equal in rank?
  • How to create a hyperlink to an executable?
  • Remove all text files with non-US-ASCII text encoding from current folder on Linux
  • EU citizen making unofficial crossing from non-Schengen EU country to Schengen EU country
  • Was Alexei Navalny in 2020 poisoned with Novitschok nerve agents by Russia's Federal Security Service?
  • Brainfuck to C transpiler
  • If the tidal bulge on the earth speeds the moon up, how does the moon move to a higher orbit?
  • How can the ECtHR judgement on encryption be reconciled with the UK's Online Safety act?
  • Lots of electrical noise at boost converter output
  • How to create an alphanumerical Hash string with fixed length?
  • Two 10-letter words consisting of 20 unique letters?
  • Who is this chess player?
  • On a tinted (reflective) window, why do I need to look from up close to see inside?
  • Regular orbits for automorphisms of finite simple groups
  • Legal definition of a "criminal record"
  • How to fit a product of linear expressions?

bash assign if to variable

LinuxSimply

Home > Bash Scripting Tutorial > Bash Conditional Statements > If Statement in Bash > Check If a Variable is Set or Not in Bash [4 Methods]

Check If a Variable is Set or Not in Bash [4 Methods]

Nadiba Rahman

Setting a variable is a process that initializes the variable, assigning it a value that can be accessed and used within the script. When a variable is “set,” it means that a value has been assigned to that variable. Note that, when a variable is declared with an empty string ( “” ), it indicates the variable has already been set . Generally, Bash offers a couple of parameters such as -v, -z, and -n to be utilized within conditional expressions to check whether a variable is set or not. In addition, the parameter expansion can be used to validate this variable check as well as to set or assign a value when the variable is not set.

In this article, I will describe 4 methods to check if a variable is set or not in Bash with different examples.

When a Variable is Considered as ‘Set’ in Bash?

In Bash scripting, a variable is considered as set or defined as long as it is declared and assigned some value. It may contain zero value or an empty string too. For instance: variable="" or variable="Linux" . On the contrary, the variable that is never created, initialized, or assigned any value, is considered as an unset or undefined variable.

4 Methods to Check If a Variable is Set or Not in Bash

Bash provides several ways to check if a variable is set or not in Bash including the options -v, -z, -n, and parameter expansion, etc. Let’s explore them in detail in the following section.

1. Using “-v” Option

The -v option in the ‘ if ’ statement checks whether a variable is set or assigned . This option returns True if the given variable has been declared previously, regardless of its value (even if it contains an empty string). Otherwise, it states that the variable is unset.

To check if a variable is set or not, use the -v option with the “[ ]” operator using the syntax if[ -v variable ] .

This script checks if the variables var1 and var2 are defined with some values or not. If the conditions are satisfied, the script echoes the respective outputs employing the echo command .

Using '-v' option for checking if variable is set

2. Using “-z” option

The -z option checks if the variable contains a value with zero length . It returns True if the specified variable is not defined or its length is zero i.e. indicating the variable is declared and initialized with an empty string. The syntax for this option is [ -z "${variable}" ] , [[ -z ${variable} ]] , or [[ -z "${variable}" ]] .

Let’s take a look at the following example using the [[ -z ${variable} ]] syntax to check if a variable is set or not:

First, when the -z option performs the conditional check, it finds that the variable ‘pqr’ is not yet declared. Thus, it echoes ‘The variable is not set.’. As well, after assigning an empty string value, the script considers the ‘pqr’ variable set i.e. having zero length, and executes ‘The variable is set with empty string.’

Checking if a variable is set or not using '-z' option

3. Using “-n” option

The -n option is used in ‘ if ’ statement for validating if the value of a variable provided is non-empty . When a variable is assigned a non-empty value, a true expression is executed i.e. indicates the variable is set . Otherwise, the variable is unset.

To check if a variable is declared/set and not empty, use the [ -n "${variable}" ] , [[ -n ${variable} ]] , or [[ -n "${variable}" ]] syntax. Here’s an example utilizing the syntax [[ -n "${variable}" ]] :

In the above code, the condition inside [[ ]] checks if the specified variable is equal to a non-empty string. If the variable is not empty, then the condition becomes true and the script displays ‘The variable is set with a non-empty value.’

Checking if a variable is set or not using '-n' option

4. Using Parameter Expansion

Parameter expansion is an effective way to check whether a variable is set. In this effort, use the syntax ${variable+value} in conjunction with the parameters -z and -n where the expression expands to the ‘value’ if the variable is already set.

Following is an example to check if a variable is set using the if [[ -z "${variable+value}" ]] syntax with the -z option. It returns True only if the variable is not declared or not set. Otherwise, the output returns nothing.

Here, the -z option within the ‘ if ’ condition checks if the variable var1 is not set yet. As it returns a true expression, the script echoes ‘var1 is unset.’.

Checking if a variable is set using parameter expansion with '-z' option

How to Assign a Default Value If a Variable is Not Set

While dealing with variables, it’s very important to assign a default value to the variable that is not declared or set, otherwise, unexpected errors may occur. In Bash, there are various types of parameter expansions that you can enlist within conditional statements to accomplish this task. These are: ${variable:-default_value} , ${variable=default_value} , variable=”default_value” . Following is an example utilizing the syntax ${variable:-default_value} where the parameter expansion substitutes the default value when a variable is not set.

Here, the -z option checks if the variable ‘name’ contains zero-length value i.e. an empty string or unset. If the condition is satisfied, ${name:-N} expands to ‘N’ and assigns the default value ‘N’ to the variable ‘name’. Finally, the script prints the assigned value of the variable.

Using parameter expansion to assign a default value to a variable that is not set

The whole article enables you to check if a variable is set in Bash and how to set or assign values to a variable when it is not set. Among all the approaches, select the one that best fits your use case and programming style.

People Also Ask

Can i assign a default value to a variable without overwriting its current value.

Yes , you can use the parameter expansion syntax var=${var:="default_value"} to assign a default value to a variable without overwriting its current value.

Can I suppress errors related to unset variables in Bash?

Yes , you can suppress errors related to unset variables using the ${variable:?error_text} syntax. If the variable is unset or null, the execution will be terminated with an error message.

How do I handle errors caused by unset variables in Bash?

To handle errors caused by unset variables, you can address set -u at the beginning of the script, perform the conditional checks employing the parameters -v , -z , and -n before using variables or set default values to the variables.

What happens if I set a variable multiple times using the default assignment?

If you set a variable multiple times that is initially unset or empty using a default assignment like ${variable:-default_value} , the variable will be set to the specified default value. But if a variable is already set, then this syntax will not overwrite the actual value of the variable.

Can I set a variable within a function if it’s not set globally?

Yes , you can set the variable within a function using the local keyword even if it’s not set globally. Here’s how:

Related Articles

  • Mastering 10 Essential Options of If Statement in Bash
  • How to Check a Boolean If True or False in Bash [Easy Guide]
  • Bash Test Operations in ‘If’ Statement
  • Check If a Variable is Empty/Null or Not in Bash [5 Methods]
  • Check If Environment Variable Exists in Bash [6 Methods]
  • Bash Modulo Operations in “If” Statement [4 Examples]
  • How to Use “OR”, “AND”, “NOT” in Bash If Statement [7 Examples]
  • Evaluate Multiple Conditions in Bash “If” Statement [2 Ways]
  • Using Double Square Brackets “[[ ]]” in If Statement in Bash
  • 6 Ways to Check If a File Exists or Not in Bash
  • How to Check If a File is Empty in Bash [6 Methods]
  • 7 Ways to Check If Directory Exists or Not in Bash
  • Negate an “If” Condition in Bash [4 Examples]
  • Check If Bash Command Fail or Succeed [Exit If Fail]
  • How to Write If Statement in One Line? [2 Easy Ways]
  • Different Loops with If Statements in Bash [5 Examples]
  • Learn to Compare Dates in Bash [4 Examples]

<< Go Back to If Statement in Bash | Bash Conditional Statements | Bash Scripting Tutorial

Nadiba Rahman

Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment Cancel reply

Save my name, email, and website in this browser for the next time I comment.

How to Assign One Variable to Another in Bash

  • Linux Howtos
  • How to Assign One Variable to Another in …

Declare a Variable in Bash

Assign one variable to another in bash.

How to Assign One Variable to Another in Bash

In Bash, a variable is created by giving its reference a value. Although the built-in declare statement in Bash is not required to declare a variable directly, it is frequently used for more advanced variable management activities.

To define a variable, all you have to do is give it a name and a value. Your variables should have descriptive names that remind you of their relevance. A variable name cannot contain spaces or begin with a number.

However, it can begin with an underscore. Apart from that, any combination of uppercase and lowercase alphanumeric characters is permitted.

To create a variable in the Bash shell, you must assign a value to that variable.

Here, varname is the name of the newly created variable, and value is the value assigned to the variable. A value can be null.

Let’s look at an example.

Using the echo command, we can see the value of a variable. Whenever you refer to the value of a variable, you must prefix it with the dollar symbol $ , as seen below.

Let’s put all of our variables to work at the same time.

We can run dest=$source to assign one variable to another. The dest denotes the destination variable, and $source denotes the source variable.

Let’s assign variable a to variable b .

Hence, we can easily assign the value of one variable to another using the syntax above.

Related Article - Bash Variable

  • How to Multiply Variables in Bash
  • How to Execute Commands in a Variable in Bash Script
  • How to Increment Variable Value by One in Shell Programming
  • Bash Variable Scope
  • How to Modify a Global Variable Within a Function in Bash
  • Variable Interpolation in Bash Script

You are using an outdated browser. Please upgrade your browser to improve your experience.

Automate Endpoint Configurations with Scripts for macOS Devices

Use Scripts to run Bash, Python 3, or Zsh for endpoint configurations on macOS devices using Workspace ONE UEM.

Important : Scripts are not permitted to be assigned to Employee-Owned devices for privacy reasons.

Scripts Description

With Scripts, located in the main navigation under Resources , you can push code to macOS devices to do various configuration processes. For example, push a Bash script that changes the device's hostname.

Use Variables in your scripts to protect sensitive static data like passwords and API keys, or use UEM lookup values for dynamic data such as device ID and user name. You can also make this code available to your macOS users so they can run it on their devices when needed. Make code available by integrating the Workspace ONE Intelligent Hub with Scripts so that users can access the code in the Apps area of the catalog.

Note : If you are publishing scripts to less than 2000 (default value) devices, the devices are notified immediately to fetch the resource. However, if the smart groups assigned have more than 2000 devices, then the devices will receive the resource the next time the devices checks-in with Workspace ONE UEM console.

How Do You Know Your Scripts Are Successful?

You can find out if Scripts ran successfully using the Scripts tab in a device's Device Details page. In the Workspace ONE UEM console, go to the applicable organization group, select Devices > List View , and choose an applicable device. On the Scripts tab, look in the Status column for an Executed or Failed status. Statuses depend on the exit code (also known as error code or return code).

  • Executed - Workspace ONE UEM displays this status after the exit code returns a 0.
  • Failed - Workspace ONE UEM displays this status after the exit code returns any value that is not a 0.

Create a Script for macOS Devices

Scripts for macOS managed by Workspace ONE UEM supports using Bash, Python 3, or Zsh to run code on end user devices. Integrate Scripts with the Workspace ONE Intelligent Hub for macOS and enable self-service to Scripts for your users.

Scripts functionality requires Intelligent Hub 20.10 and Workflow Engine 20.10 for macOS.

  • In the Workspace ONE UEM console, navigate to Resources > Scripts > Add .

The Script user interface

Select macOS .

Configure the script settings for the General tab.

Click Next .

Configure the script settings for the Details tab.

In the Variables tab, configure key and value pairs to be accessible in the scripting environment:

Add static values, such as API keys, service account names or password by providing the key and the value of the variable. Or, add dynamic UEM lookup values such as \{enrollmentuser\} by providing a key name and then selecting the lookup value icon. To use variables in a Bash/Zsh script, reference the variable directly by name using $myvariable . To use variables in a Python 3 script, you must first import the os module, then use the getenv method like os.getenv\('myvariable'\) .

For instance, if the variable definition has a key named SystemAccount and a value of admin01 , the script can assign the variable to a script-variable, named account as shown below:

Click Save .

You have successfully created a Script.

What to do next:

After creating Scripts, you can assign it to smart groups.

To assign the script to a smart group, select a script from the Scripts page, and click Assign .

Click New Assignment and enter Assignment Name and select the smart group. Click Next .

In the Deployment page, select any of the following triggers:

Enable Show In Hub (optional) to show your App Catalog Customization settings for the script in the Workspace ONE Intelligent Hub. You can deactivate this option to hide a script from assigned smart groups in the catalog.

The New Assignment Deployment page showing Triggers

You have successfully assigned a Script to a smart group and added triggers.

View Scripts in Device Details

Navigate to the Scripts tab in a device's Device Details to view the execution status of your Scripts.

  • Navigate to Device > Details View > Scripts .
  • In the list you can view name of the script, last execution time, status, and log details.

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

[Proposal]: Allow pattern matching to assign to new variable in more cases #7945

@OJacot-Descombes

OJacot-Descombes Feb 17, 2024

Beta Was this translation helpful? Give feedback.

Replies: 2 comments · 4 replies

{{editor}}'s edit, 333fred feb 17, 2024 maintainer.

@OJacot-Descombes

OJacot-Descombes Feb 17, 2024 Author

@Unknown6656

Unknown6656 Feb 18, 2024

Ojacot-descombes feb 18, 2024 author, tahirahmadov feb 17, 2024.

@OJacot-Descombes

  • Numbered list
  • Unordered list
  • Attach files

Select a reply

  • Developing Applications with Oracle Visual Builder in Oracle Integration Generation 2
  • Develop Applications
  • Work with JavaScript Action Chains
  • Built-In Actions

Add an Assign Variable Action

You use an Assign Variable action to assign a local, page, flow, or application variable a value. This action can also be used to create a local variable.

For example, if your action chain sends a request to a GET endpoint, you can use the Assign Variable action to map the response to a page variable that's bound to a page component. Or, suppose you want to capture the ID of an item selected in a list. You could use a Selection event to start an action chain that assigns the selected item’s ID to a variable.

To use an Assign Variable action to create a local variable:

  • Enter the variable's name in the Variable field and hit Enter on your keyboard.
  • Use the Type drop-down to select its data type.

Description of jsac-assign-new-local-var.png follows

To use an Assign Variable action for a value assignment:

  • Drag the action from the Actions palette onto the canvas, dropping the action either at the bottom edge of the action it is to follow, or at the top edge of the action it is to precede.
  • Double-click the action in the Actions palette to add it to an empty canvas or to the end of an action chain.
  • On the canvas, select the action you want the new action to follow, then double-click the new action in the Actions palette.

Description of jsac-assign-variables-action.jpg follows

  • To set the variable's value, hover over the far-right side of the Value property and either click the down arrow to choose the value, or click fx to create an expression for the value.

Description of jsac-assign-another-var.png follows

IMAGES

  1. How to Write a Bash IF-Statement (Conditionals)

    bash assign if to variable

  2. [Solved] Unix Bash

    bash assign if to variable

  3. Using If Else in Bash Scripts [Examples]

    bash assign if to variable

  4. How to use Variables in Bash

    bash assign if to variable

  5. How to Use If Statement in Bash Scripting

    bash assign if to variable

  6. How to Use Variables in Bash Shell Scripts

    bash assign if to variable

VIDEO

  1. assign variable in c program||#cprogramming #coding #cprogrammingvideo #tutorial #shorts #trending

  2. Section-5: Vidoe-10 : Command Line Arguments to provide inputs for Variables of Bash Shell Script

  3. Geometry Bash 2 Trailer

  4. Difference between local and global variable

  5. Project 1 # Shell scripting

  6. 90. Max Subarray Sum

COMMENTS

  1. BASH: Basic if then and variable assignment

    1 Answer Sorted by: 36 By standard it should be if [ "$time" -gt 300 ] && [ "$time" -lt 900 ] then mod=2 else mod=0 fi In normal shell scripts you use [ and ] to test values. There are no arithmetic-like comparison operators like > and < in [ ], only -lt, -le, -gt, -ge, -eq and -ne.

  2. How do I assign a value to a BASH variable if that variable is null

    - Unix & Linux Stack Exchange How do I assign a value to a BASH variable if that variable is null/unassigned/falsey? [duplicate] Ask Question Asked 3 years, 7 months ago Modified 1 year, 5 months ago Viewed 102k times 78 This question already has answers here : Using "$ {a:-b}" for variable assignment in scripts (4 answers) Closed 3 years ago.

  3. How to Work with Variables in Bash

    Key Takeaways Variables are named symbols representing strings or numeric values. They are treated as their value when used in commands and expressions. Variable names should be descriptive and cannot start with a number or contain spaces. They can start with an underscore and can have alphanumeric characters.

  4. bash

    This technique allows for a variable to be assigned a value if another variable is either empty or is undefined. NOTE: This "other variable" can be the same or another variable. excerpt $ {parameter:-word} If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

  5. assign string to variable with if else condition [duplicate]

    Unable to assign values to array within -exec command of find result Hot Network Questions Rotation of instances aligned to curve tangent and normals of another object

  6. How to Assign Variable in Bash Script? [8 Practical Cases]

    In Bash scripts, variable assignment follows a straightforward syntax, but it offers a range of options and features that can enhance the flexibility and functionality of your scripts. In this article, I will discuss modes to assign variable in the Bash script.

  7. bash

    1 For the record, "true" and "false" there are no different from any other string such as "you" and "me". Also bash is not programming language like Java or so, therefore you expectation that it has builtin facility that automagically converts a boolean type value (which isn't exactly a thing in bash either) to a string was never real. - Tom Yan

  8. Check If a Variable is Set or Not in Bash [4 Methods]

    1. Using "-v" Option The -v option in the ' if ' statement checks whether a variable is set or assigned. This option returns True if the given variable has been declared previously, regardless of its value (even if it contains an empty string). Otherwise, it states that the variable is unset.

  9. Unix Bash

    Unix Bash - Assign if/else to Variable Ask Question Asked 8 years, 10 months ago Modified 6 years, 3 months ago Viewed 33k times 8 I have been creating to assign the output of if/else to a variable but keep on getting an error. For Example: mathstester=$ (If [ 2 = 2 ] Then echo equal Else echo "not equal" fi)

  10. How to Use Variables in Bash Shell Scripts

    Using variables in bash shell scripts. In the last tutorial in this series, you learned to write a hello world program in bash. #! /bin/bash echo 'Hello, World!'. That was a simple Hello World script. Let's make it a better Hello World. Let's improve this script by using shell variables so that it greets users with their names.

  11. How to Assign Default Value to a Variable Using Bash

    How to Assign Default Value to a Variable Using Bash Last updated: December 3, 2023 Written by: Jimmy Azar Scripting bash echo 1. Overview When dealing with variables in shell scripting, it's important to account for the fact that a variable may have one of several states: assigned value unset null string

  12. bash

    So what you wrote assigns an empty value to thefile; furthermore, since the assignment is grouped with a command, it makes thefile an environment variable and the assignment is local to that particular command, i.e. only the call to ls sees the assigned value. You want to capture the output of a command, so you need to use command substitution:

  13. Bash Assign Output of Shell Command To Variable

    To assign output of any shell command to variable in bash, use the following command substitution syntax: var =$ ( command-name-here) var =$ ( command-name-here arg1) var =$ (/ path / to /command) var =$ (/ path / to /command arg1 arg2) OR use backticks based syntax as follows to assign output of a Linux or Unix command to a variable:

  14. How to Assign One Variable to Another in Bash

    To create a variable in the Bash shell, you must assign a value to that variable. Syntax: varname=value. Here, varname is the name of the newly created variable, and value is the value assigned to the variable. A value can be null. Let's look at an example. $ me=superman $ this_year=2022.

  15. Linux Bash: Multiple Variable Assignment

    Assigning multiple variables in a single line of code is a handy feature in some programming languages, such as Python and PHP. In this quick tutorial, we'll take a closer look at how to do multiple variable assignment in Bash scripts. 2. Multiple Variable Assignment

  16. bash

    From Bash manual, a parameter is set if it has been assigned a value. In bash, are the following two different concepts: a variable exists a variable has been assigned a value, i.e. is set? unset removes a variable or function. Does unset make a variable become non-existent, or still exists but become not assigned any value?

  17. Automate Endpoint Configurations with Scripts for macOS Devices

    Click Next.. In the Variables tab, configure key and value pairs to be accessible in the scripting environment:. Add static values, such as API keys, service account names or password by providing the key and the value of the variable. Or, add dynamic UEM lookup values such as \{enrollmentuser\} by providing a key name and then selecting the lookup value icon.

  18. Assigning default values to shell variables with a single command in bash

    12 Answers Sorted by: 2378 Very close to what you posted, actually. You can use something called Bash parameter expansion to accomplish this. To get the assigned value, or default if it's missing: FOO="$ {VARIABLE:-default}" # FOO will be assigned 'default' value if VARIABLE not set or null.

  19. [Proposal]: Allow pattern matching to assign to new variable in more

    This tests the property P for being not null and assigns its value to the new variable s if the result is true. This is not very readable. This is not very readable. It would be more readable if we could write:

  20. bash

    8 Answers Sorted by: 93 local t1=$ (exit 1) tells the shell to: run exit 1 in a subshell; store its output (as in, the text it outputs to standard output) in a variable t1, local to the function. It's thus normal that t1 ends up being empty. ( $ () is known as command substitution .) The exit code is always assigned to $?, so you can do

  21. Add an Assign Variable Action

    To set the variable's value, hover over the far-right side of the Value property and either click the down arrow to choose the value, or click fx to create an expression for the value.; If you need to do another assignment, click the + Assign Variable button in the Properties pane: Description of the illustration jsac-assign-another-var.png

  22. Assigning one variable to another in Bash?

    Assigning one variable to another in Bash? Ask Question Asked 9 years, 1 month ago Modified 1 year, 3 months ago Viewed 60k times 16 I have a doubt. When i declare a value and assign to some variable, I don't know how to reassign the same value to another variable. See the code snippet below.

  23. shell

    Is there a way to create bash variables and assign them values via a loop? Something along the lines of: #!/bin/bash c=0 for file in $ ( ls ); do var"$c"="$file"; let c=$c+1; done EDIT: Thank you to @Costas and @mdpc for pointing out this would be a poor alternative to a list; the question is theoretical only. bash shell-script Share

  24. bash

    If I want to have my bash script exit whenever an unset variable is expanded, I can use set -u. ... Assigning default values to shell variables with a single command in bash. 3525. How to concatenate string variables in Bash. 3510. How to check if a string contains a substring in Bash.