Using Conditionals in Bash

Table of contents

Bash test commands, compounding comparison operators, integer comparison operators, string evaluation operators, file evaluating operators, if statements, if-else statements, if-elif-else statements, nested if statements, case statements, handling script failures using conditionals, storing script output.

  • ‣ Loops In Bash
  • ‣ Understanding Bash Shell
  • ‣ Bash Variables Explained
  • ‣ Shell Script Functions Guide
  • ‣ Bash File Reading

Learn More About Earthly

Earthly makes builds super simple. Learn More

Using Conditionals in Bash

Mdu Sibisi %

In this Series

Table of Contents

Understand Bash conditionals with our new article. Earthly ensures consistent builds in different environments. Learn more about Earthly .

Bash (bourne again shell) has been around since 1989 and owes its longevity to its usefulness and flexibility. While it’s the default login and command shell for most Linux distros, its value extends beyond that.

Bash can be used as a fully-fledged programming language and as a tool to automate repetitive and complex computational tasks. However, as with any other programming language, you need to understand how to manage Bash’s control flow to truly get the most out of it.

Whether you’re a power user writing simple scripts to help organize your files or a data scientist curating large sets of data, efficiently performing these tasks is nearly impossible without a conditional statement or two.

The following guide will introduce you to Bash’s collection of conditionals and will teach you how to become proficient in their uses.

What Are Bash Conditionals

Bash conditionals let you write code that performs different tasks based on specified checks. These checks can be based on a simple assessment that results in a true or false result. Alternatively, a conditional may be in the form of a multiple case check where a number of values are assessed before an operation is performed.

Conditionals make programmers’ lives easier and help prevent and handle errors and failures. Without them, you’d have to manually perform checks before running a script or program. However, to build functioning conditionals and test expressions in Bash, you need a working knowledge of its test commands and operators. Before you review all the conditionals available, you need to learn how to build proper tests, starting with Bash’s test commands.

Bash can be a very loose and flexible language. Many concrete concepts you’d find in other programming languages are absent, and you have to use conventional design patterns to make Bash work the same way other programming languages do.

For instance, conditionals assess the exit status of a command. If you want Bash to mimic Boolean evaluations, you’ll need to use a specialized command. There are three ways you can test an expression in Bash:

  • test : takes an expression as its argument and evaluates it ( ie it exits with a status code dictated by the expression). It returns 0 to indicate that an expression is true. A value other than 0 ( ie 1 ) would indicate that it’s false. For instance, test $n -gt 5 evaluates if the value of the variable $n , is greater than five, and returns an exit code of 0 if true.
You can use the $? variable to see the return value of the last executed command ( ie to see if the test command evaluated its expression to true or false).
  • [ : is a shorthand alternative version of the test command. It does exactly what the test command does but with a slightly different syntax: [ $n -gt 5 ] .
Note: The [ built-in requires at least a single space after the opening bracket and one before the closing bracket.
  • [[ : is an improved version of the [ built-in. It also evaluates an expression but with a few improvements and caveats. For instance, Bash doesn’t perform glob expansion or word splitting when parsing the command’s argument. This makes it a more versatile command. [[ is also slightly more lenient on syntax and allows you to run more modernized tests and conditions.

For instance, you can compare integers using the < and > operators. [[ $n > 10 ]] tests if the value of the n variable is greater ( -gt ) than ten. It will return an exit code based on this test. On the other hand, [ $n > 10 ] creates a (empty) file called 10 , and in most cases, it will return an exit status of 0 (barring that nothing stops it from creating the file).

Again, because the [[ command skips glob expansion and word splitting, it makes testing regular expressions easier. For instance, the arguments of the command [[ $n =~ [1-10] ]] will cause the [ command to fail. For this reason, many use cases require using this command over the test keyword or [ built-in.

Bash Test Operators

Now that you, hopefully, understand how Bash’s test commands work, you can learn how to form test expressions. The core of the expressions is test operators . If you want to take full advantage of conditionals, you need to have a healthy understanding of them.

Bash has a large variety of test operators that apply to different variable types and situations. These operators are just flags passed to the test commands and include the following:

Compounding comparison operators allow you to combine test expressions. They return a value based on a test performed on multiple expressions:

  • -a : is the and operator. It lets you test multiple conditions and returns true if all conditions are true ( ie if [ $n -gt 10 -a $n -lt 15 ] ).
  • -o : is the or operator. It lets you test multiple conditions and returns true if one or more conditions are true ( ie if [ $n -gt 10 -o $n -lt 15 ] ).

Integer comparison operators let you build expressions that compare whole numbers in Bash:

  • -eq : tests if two values/variables are equal ( = or == )
  • -ne : checks if two values/variables are not equal ( != )
  • -gt : checks if one value is greater than another ( > )
  • -ge : checks if one value is greater than or equal to another ( >= )
  • -lt : checks if one value is less than another ( < )
  • -le : checks if one value is equal or less than another ( <= )
You can use the symbols ( < , > , = , != , etc.) in place of the above word-based operators when using the [[ built-in.

String evaluation operators let you compare and evaluate strings of text in Bash:

  • == or = : checks if two strings are equal
  • != : checks if two strings are not equal to each other
  • < : checks if one string is less than another using the ASCII sorting order
  • > : checks if one string is greater than another using the ASCII sorting order
  • -z : returns true if the string is empty or null (has a length of zero)
  • -n : returns true if a string is not null

These advanced operators let you assess and compare files in Bash:

  • -e : validates the existence of a file (returns true if a file exists)
  • -f : validates if the variable is a regular file (not a folder, directory, or device)
  • -d : checks if the variable is a directory
  • -h (or -L ): validates if the variable is a file that is a symbolic link
  • -b : checks if a variable is a block special file
  • -c : verifies if a variable is a character special file
  • -p : checks if a file is a pipe
  • -S : checks if a file is a socket
  • -s : verifies if the size of the file is above zero (returns true if the file is greater than 0 bytes)
  • -t : validates if the file is associated with a terminal device
  • -r : checks if the file has read permissions
  • -w : verifies if the file has write permissions
  • -x : checks if the file has execute permissions
  • -g : checks if the SGID flag is set on a file
  • -u : verifies if the SUID flag is set on a file
  • -k : checks if the sticky bit is set on a file
  • -O : verifies if you’re the owner of a file
  • -G : validates if the group ID is the same as yours
  • -N : validates if a file was modified since it was last read
  • -nt : compares the creation dates of two files to see if one file (file 1) is newer than the other (file 2)
  • -ot : compares the creation dates of two files to verify if one file (file 1) is older than the other (file 2)
  • -ef : checks if two variables are hard links to the same file

Conditional Statements

The first category of conditionals you’ll look at is known as conditional statements. Each statement assesses a singular condition (which can be compounded from multiple conditions) and performs an action (or list of actions).

The if statement is the most commonly used conditional in any programming language. The structure of a simple if statement is as follows:

The first line assesses a condition (any command). The fi indicates the end of the if statement (along with its body). Bash evaluates a command’s exit code before performing (or skipping) an action (or set of actions). If a command returns an exit code of 0 , it has run successfully. In that case, the if statement will run the command(s) between the then and fi keywords.

A status code with any other value (1–255) denotes a failure and will cause the if statement to skip over the statements between the if’s body. While Bash doesn’t have true built-in conditions, you can co-opt and use its command status codes as a makeshift boolean, where 0 is true and any other value is false. You also have true and false , which are actual commands that return 0 and 1 , respectively.

Take a look at the following example:

The code here first assigns the number of files in the current directory to a variable ( n ). It then uses the test operator -lt to test if the number count is less than ten. If the test condition is true, the command ( [ $n -lt 10 ] ) will exit with a status of 0 , returning an exit code of 0 . Then it displays a message informing the user that there are less than ten files in this particular directory.

Of course, this sample can be repurposed and used for more practical applications, like deleting files in a folder when they exceed a certain number.

An if-else statement allows you to call an alternative command when an if statement’s condition evaluates to false ( ie when its command returns an error status code). In most cases, the else portion of the statement provides you a chance to perform some cleanup. For instance, you can use it to exit the script or inform the user that a condition has not been met. The syntax of the if-else statement is as follows:

You can modify the previous example:

This time, the if-else informs the user that there are more than ten files instead of just exiting the script when it doesn’t meet the first condition.

The if-elif-else statement lets you add more functionality to the basic if and if-else statements. You can test multiple conditions and run separate commands when a condition is met.

Because things in the real world aren’t always limited to two alternatives, you need conditionals with more nuance to suit complex use cases. The if-elif-else statement provides this subtlety. Its structure is as follows:

Again, you can modify the last example:

elif is essentially a shorthand of an else-if statement that you may recognize from other fully formed programming languages. In the example above, you check if there are less than ten files. If there are more than ten files, your else-if conditional expression will check if there are less than fifteen files. If both conditions are not met—in this case, the directory has more than fifteen files—then the script will display a message indicating this.

If you want to add more refinement to your if and elif conditionals, you can use a nested or embedded if statement. A nested if lets you perform an additional check after a condition is met by an if statement. The structure looks like this:

Of course, Bash doesn’t require you to indent code. However, it’s easier to read the above syntax if you do. Here’s how the nested if looks in action:

Here, you’ve added a nested if to your previous example. To start, it checks if the current directory has less than ten files. If the command runs successfully, it performs another check to see if there are more than five files and then displays a message accordingly.

Case statements are one of the most important control flow tools for advanced programming. They work similarly to if-elif-else statements, but when employed correctly, they can help produce cleaner code. The syntax for a case statement is as follows:

Here, rather than using a condition, you test a variable that will be compared against the patterns, and when a match is found, the corresponding action(s) will be performed.

The structure may be a little hard for beginners to understand, but the more you use it, the more comfortable you’ll become. Again, you can modify the previous examples with case statements:

This time, the example takes the file count and assesses it against twelve different patterns, which are all simple numbers. It displays a message with every pattern it suits. The pattern * acts as a catchall and will match if none of the other patterns match.

You can also combine multiple patterns with | :

As you may have noted, the command list associated with each pattern ends in ;; . However, you can also use ;& or ;;& . If you use ;& , the execution will continue with the next clause even if the next pattern doesn’t match (a fall through).

If you use ;;& , the execution will continue with the next clause, only if the pattern matches:

As this guide has discussed, each command returns an exit code. Conditionals use these exit codes to determine which code should be executed next. If a function, command, or script should fail, a well-placed conditional can catch and handle this failure.

Bash has more sophisticated tools for error handling ; however, if you’re performing quick and dirty script failure handling, simple if or case statements should be sufficient.

When troubleshooting or keeping a record of successful and failed scripts, you can output the results to an external file. The above guide has already touched on how you can output the results of a command using the > operator. You can also keep a record of script errors by using a combination of exit code tests, conditionals, and this operator. Here’s an example:

The above snippet will check if the current directory has less than ten files. If it does, it will output a success message to a file named success.txt . If it fails, it will redirect the echo command’s output and place it in a file named fail.txt .

The > redirection operator will create a new file and write the output on that new file if the file doesn’t exist. However, if the file does exist, the command will overwrite its contents. Thus, you should use the >> operator if you want to append contents to an existing file. These are the simplest ways to redirect output from Bash and place it on an external file.

Learning conditionals could be your final hurdle to truly understanding Bash and mastering it. Up until now, you may have underestimated Bash’s true capabilities. You may even find that learning about Bash’s various conditional statements, expressions, and operations inspires you to rewrite old scripts and improve them with better flow control.

But if you do, remember to utilize the correct syntax. Bash (especially sh) is case- and space-sensitive. Then you can transfer what you’ve learned from Bash and use it with Earthly . Earthly lets you define and deploy your build using a Git-aware syntax that is strikingly similar to Bash.

Because Earthly’s builds are neatly encapsulated and language-independent, they’re easier to initiate and manage. If you’re trying to build and deploy repeatable multiplatform software, Earthly is a great solution.

Earthly Cloud: Consistent, Fast Builds, Any CI Consistent, repeatable builds across all environments. Advanced caching for faster builds. Easy integration with any CI. 6,000 build minutes per month included.

Get Started Free

bash conditional variable assignment

12 minute read

Learn how to use loops in Bash to control the flow of your programs. This article covers the different types of loops in Bash, including `while`, `until`, an...

bash conditional variable assignment

19 minute read

Learn the ins and outs of bash scripting and how it can make your life easier. From understanding shebangs to error handling and variable naming, this articl...

bash conditional variable assignment

9 minute read

Learn the basics of bash variables and how they work in the UNIX shell. Discover how to define and access local shell variables, work with arrays, handle com...

bash conditional variable assignment

13 minute read

Learn the fundamentals of shell scripting functions and arguments in this comprehensive guide. Discover how to create functions, pass arguments, use variable...

bash conditional variable assignment

8 minute read

Learn how to use Bash to read files line by line, use custom delimiters, assign variables, and more. This article provides step-by-step instructions and exam...

bash conditional variable assignment

11 minute read

Learn how to manipulate strings in bash with this informative tutorial. From concatenating strings to replacing parts of a string, you'll discover useful tec...

bash conditional variable assignment

Learn why using YAML for control flow configuration can lead to complex and hard-to-understand code, and why it's better to use existing programming language...

bash conditional variable assignment

27 minute read

Learn how to automate common tasks in software development using shell scripts. From file backups to log analysis and system maintenance, this article provid...

bash conditional variable assignment

18 minute read

Learn fifteen essential Linux terminal commands that will supercharge you as a Linux user. From searching for patterns in files to managing permissions and s...

bash conditional variable assignment

Learn how to use the `echo` command in Linux to display text, format output, add and overwrite text in files, display variables, search for files, and more. ...

Next: Grouping Commands , Previous: Looping Constructs , Up: Compound Commands   [ Contents ][ Index ]

3.2.5.2 Conditional Constructs

The syntax of the if command is:

The test-commands list is executed, and if its return status is zero, the consequent-commands list is executed. If test-commands returns a non-zero status, each elif list is executed in turn, and if its exit status is zero, the corresponding more-consequents is executed and the command completes. If ‘ else alternate-consequents ’ is present, and the final command in the final if or elif clause has a non-zero exit status, then alternate-consequents is executed. The return status is the exit status of the last command executed, or zero if no condition tested true.

The syntax of the case command is:

case will selectively execute the command-list corresponding to the first pattern that matches word . The match is performed according to the rules described below in Pattern Matching . If the nocasematch shell option (see the description of shopt in The Shopt Builtin ) is enabled, the match is performed without regard to the case of alphabetic characters. The ‘ | ’ is used to separate multiple patterns, and the ‘ ) ’ operator terminates a pattern list. A list of patterns and an associated command-list is known as a clause .

Each clause must be terminated with ‘ ;; ’, ‘ ;& ’, or ‘ ;;& ’. The word undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal (see Shell Parameter Expansion ) before matching is attempted. Each pattern undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, process substitution, and quote removal.

There may be an arbitrary number of case clauses, each terminated by a ‘ ;; ’, ‘ ;& ’, or ‘ ;;& ’. The first pattern that matches determines the command-list that is executed. It’s a common idiom to use ‘ * ’ as the final pattern to define the default case, since that pattern will always match.

Here is an example using case in a script that could be used to describe one interesting feature of an animal:

If the ‘ ;; ’ operator is used, no subsequent matches are attempted after the first pattern match. Using ‘ ;& ’ in place of ‘ ;; ’ causes execution to continue with the command-list associated with the next clause, if any. Using ‘ ;;& ’ in place of ‘ ;; ’ causes the shell to test the patterns in the next clause, if any, and execute any associated command-list on a successful match, continuing the case statement execution as if the pattern list had not matched.

The return status is zero if no pattern is matched. Otherwise, the return status is the exit status of the command-list executed.

The select construct allows the easy generation of menus. It has almost the same syntax as the for command:

The list of words following in is expanded, generating a list of items, and the set of expanded words is printed on the standard error output stream, each preceded by a number. If the ‘ in words ’ is omitted, the positional parameters are printed, as if ‘ in "$@" ’ had been specified. select then displays the PS3 prompt and reads a line from the standard input. If the line consists of a number corresponding to one of the displayed words, then the value of name is set to that word. If the line is empty, the words and prompt are displayed again. If EOF is read, the select command completes and returns 1. Any other value read causes name to be set to null. The line read is saved in the variable REPLY .

The commands are executed after each selection until a break command is executed, at which point the select command completes.

Here is an example that allows the user to pick a filename from the current directory, and displays the name and index of the file selected.

The arithmetic expression is evaluated according to the rules described below (see Shell Arithmetic ). The expression undergoes the same expansions as if it were within double quotes, but double quote characters in expression are not treated specially are removed. If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1.

Return a status of 0 or 1 depending on the evaluation of the conditional expression expression . Expressions are composed of the primaries described below in Bash Conditional Expressions . The words between the [[ and ]] do not undergo word splitting and filename expansion. The shell performs tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal on those words (the expansions that would occur if the words were enclosed in double quotes). Conditional operators such as ‘ -f ’ must be unquoted to be recognized as primaries.

When used with [[ , the ‘ < ’ and ‘ > ’ operators sort lexicographically using the current locale.

When the ‘ == ’ and ‘ != ’ operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below in Pattern Matching , as if the extglob shell option were enabled. The ‘ = ’ operator is identical to ‘ == ’. If the nocasematch shell option (see the description of shopt in The Shopt Builtin ) is enabled, the match is performed without regard to the case of alphabetic characters. The return value is 0 if the string matches (‘ == ’) or does not match (‘ != ’) the pattern, and 1 otherwise.

If you quote any part of the pattern, using any of the shell’s quoting mechanisms, the quoted portion is matched literally. This means every character in the quoted portion matches itself, instead of having any special pattern matching meaning.

An additional binary operator, ‘ =~ ’, is available, with the same precedence as ‘ == ’ and ‘ != ’. When you use ‘ =~ ’, the string to the right of the operator is considered a POSIX extended regular expression pattern and matched accordingly (using the POSIX regcomp and regexec interfaces usually described in regex (3)). The return value is 0 if the string matches the pattern, and 1 if it does not. If the regular expression is syntactically incorrect, the conditional expression returns 2. If the nocasematch shell option (see the description of shopt in The Shopt Builtin ) is enabled, the match is performed without regard to the case of alphabetic characters.

You can quote any part of the pattern to force the quoted portion to be matched literally instead of as a regular expression (see above). If the pattern is stored in a shell variable, quoting the variable expansion forces the entire pattern to be matched literally.

The pattern will match if it matches any part of the string. If you want to force the pattern to match the entire string, anchor the pattern using the ‘ ^ ’ and ‘ $ ’ regular expression operators.

For example, the following will match a line (stored in the shell variable line ) if there is a sequence of characters anywhere in the value consisting of any number, including zero, of characters in the space character class, immediately followed by zero or one instances of ‘ a ’, then a ‘ b ’:

That means values for line like ‘ aab ’, ‘ aaaaaab ’, ‘ xaby ’, and ‘ ab ’ will all match, as will a line containing a ‘ b ’ anywhere in its value.

If you want to match a character that’s special to the regular expression grammar (‘ ^$|[]()\.*+? ’), it has to be quoted to remove its special meaning. This means that in the pattern ‘ xxx.txt ’, the ‘ . ’ matches any character in the string (its usual regular expression meaning), but in the pattern ‘ "xxx.txt" ’, it can only match a literal ‘ . ’.

Likewise, if you want to include a character in your pattern that has a special meaning to the regular expression grammar, you must make sure it’s not quoted. If you want to anchor a pattern at the beginning or end of the string, for instance, you cannot quote the ‘ ^ ’ or ‘ $ ’ characters using any form of shell quoting.

If you want to match ‘ initial string ’ at the start of a line, the following will work:

but this will not:

because in the second example the ‘ ^ ’ is quoted and doesn’t have its usual special meaning.

It is sometimes difficult to specify a regular expression properly without using quotes, or to keep track of the quoting used by regular expressions while paying attention to shell quoting and the shell’s quote removal. Storing the regular expression in a shell variable is often a useful way to avoid problems with quoting characters that are special to the shell. For example, the following is equivalent to the pattern used above:

Shell programmers should take special care with backslashes, since backslashes are used by both the shell and regular expressions to remove the special meaning from the following character. This means that after the shell’s word expansions complete (see Shell Expansions ), any backslashes remaining in parts of the pattern that were originally not quoted can remove the special meaning of pattern characters. If any part of the pattern is quoted, the shell does its best to ensure that the regular expression treats those remaining backslashes as literal, if they appeared in a quoted portion.

The following two sets of commands are not equivalent:

The first two matches will succeed, but the second two will not, because in the second two the backslash will be part of the pattern to be matched. In the first two examples, the pattern passed to the regular expression parser is ‘ \. ’. The backslash removes the special meaning from ‘ . ’, so the literal ‘ . ’ matches. In the second two examples, the pattern passed to the regular expression parser has the backslash quoted (e.g., ‘ \\\. ’), which will not match the string, since it does not contain a backslash. If the string in the first examples were anything other than ‘ . ’, say ‘ a ’, the pattern would not match, because the quoted ‘ . ’ in the pattern loses its special meaning of matching any single character.

Bracket expressions in regular expressions can be sources of errors as well, since characters that are normally special in regular expressions lose their special meanings between brackets. However, you can use bracket expressions to match special pattern characters without quoting them, so they are sometimes useful for this purpose.

Though it might seem like a strange way to write it, the following pattern will match a ‘ . ’ in the string:

The shell performs any word expansions before passing the pattern to the regular expression functions, so you can assume that the shell’s quoting takes precedence. As noted above, the regular expression parser will interpret any unquoted backslashes remaining in the pattern after shell expansion according to its own rules. The intention is to avoid making shell programmers quote things twice as much as possible, so shell quoting should be sufficient to quote special pattern characters where that’s necessary.

The array variable BASH_REMATCH records which parts of the string matched the pattern. The element of BASH_REMATCH with index 0 contains the portion of the string matching the entire regular expression. Substrings matched by parenthesized subexpressions within the regular expression are saved in the remaining BASH_REMATCH indices. The element of BASH_REMATCH with index n is the portion of the string matching the n th parenthesized subexpression.

Bash sets BASH_REMATCH in the global scope; declaring it as a local variable will lead to unexpected results.

Expressions may be combined using the following operators, listed in decreasing order of precedence:

Returns the value of expression . This may be used to override the normal precedence of operators.

True if expression is false.

True if both expression1 and expression2 are true.

True if either expression1 or expression2 is true.

The && and || operators do not evaluate expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression.

Brandon Rozek

Photo of Brandon Rozek

PhD Student @ RPI studying Automated Reasoning in AI and Linux Enthusiast.

Conditional Assignment in Bash

bash conditional variable assignment

Published on June 19, 2022

Updated on February 9, 2023

Many programming languages include an quick way to perform a conditional assignment. That is, assigning a variable with a value based on some condition. Normally this is done through a ternary operator. For example, here is how to write it in Javascript

The variable ageType is dependent upon the value of age . If it is above 18 then ageType = "Adult" otherwise ageType = "Child" .

A more verbose way of accomplishing the same thing is the following:

How do we do conditional assignment in Bash? One way is to make use of subshells and echoing out the values.

A common programming feature called short-circuiting makes it so that if the first condition ( [ $AGE -gt 18 ] ) is false, then it will skip the right side of the AND ( && ) expression. This is because False && True is always False . However, False || True is equal to True , so the language needs to evaluate the right part of an OR ( || ) expression.

Published a response to this? Let me know the URL :

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
  • Why configuration is so complicated
  • Is GenAI the next dot-com bubble?
  • Featured on Meta
  • New Focus Styles & Updated Styling for Button Groups
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network
  • Google Cloud will be Sponsoring Super User SE

Hot Network Questions

  • Where can I get an earth-centric map of space?
  • What is the formal version of the word "whopping"?
  • How precise should I expect to be with metronome?
  • Evaluate the binomial integral
  • Why does frequency sweeping double the frequency?
  • Improving my approach for plain water boiled brown lentils
  • How to remove freeze plugin delegate mpl core
  • Do "tinker" and "tinkerer" imply "unskillful"?
  • Two Earth engineers tasked with recreating a perpetual motion machine
  • Dialogue beginning with それにしても
  • Booking hotel relative to local or home timezone
  • What would be the grounds for the US Chamber of Commerce to sue the FTC over its new rule concerning noncompetes?
  • Is there a standard which requires a high voltage warning label on a PCB?
  • Perfect squaring of rectangles
  • What is the advantage of log file rotation?
  • 1 in 60 rule for VORs
  • Direction of angular momentum
  • When is money first mentioned in Holy Scriptures?
  • Does fully frozen food (bread) give off any moisture?
  • How Do I Explain "Be Born"?
  • Economists Working At the Intersection of Pure Math and Economics
  • Is using "oe" in place of "œ" perceived as a mistake in writing?
  • Can a judge decide a case based on their own legal knowledge?
  • Is it impossible to protect an API from data redistribution?

bash conditional variable assignment

How-To Geek

How to use bash if statements (with 4 examples).

The if statement is the easiest way to explore conditional execution in Bash scripts.

Quick Links

What is conditional execution, a simple if statement example, the elif clause, different forms of conditional test, nested if statements, the case for if, key takeaways.

Use the Linux Bash if statement to build conditional expressions with an if then fi  structure. Add elif keywords for additional conditional expressions, or the else keyword to define a catch-all section of code that's executed if no previous conditional clause was executed.

All non-trivial Bash scripts need to make decisions. The Bash if statement lets your Linux script ask questions and, depending on the answer, run different sections of code. Here's how they work.

In all but the most trivial of Bash scripts , there's usually a need for the flow of execution to take a different path through the script, according to the outcome of a decision. This is called conditional execution.

One way to decide which branch of execution to take is to use an if statement. You might hear

statements called

statements, or

statements. They're different names for the same thing.

Related: 9 Examples of for Loops in Linux Bash Scripts

The if statement says that if something is true, then do this. But if the something is false, do that instead. The "something" can be many things, such as the value of a variable, the presence of a file , or whether two strings match.

Conditional execution is vital for any meaningful script. Without it, you're very limited in what you can get your script to do. Unless it can make meaningful decisions you won't be able to take real-world problems and produce workable solutions.

The if statement is probably the most frequently used means of obtaining conditional execution. Here's how to use it in Bash scripting.

Related: How to Check If a File Exists in Linux Bash Scripts

This is the canonical form of the simplest if statement:

if [ this-condition-is-true ]

execute-these-statements

If the condition within the text resolves to true, the lines of script in the then clause are executed. If you're looking through scripts written by others, you may see the if statement written like this:

if [ this-condition-is-true ]; then

Some points to note:

  • The if statement is concluded by writing fi .
  • There must be a space after the first bracket " [ " and before the second bracket " ] " of the conditional test.
  • If you're going to put the then keyword on the same line as the conditional test, make sure you use a semi-colon " ; " after the test.

We can add an optional else clause to have some code executed if the condition test proves to be false. The else clause doesn't need a then keyword.

execute-these-statements-instead

This script shows a simple example of an if statement that uses an else  clause. The conditional test checks whether the customer's age is greater or equal to 21. If it is, the customer can enter the premises, and the then clause is executed. If they're not old enough, the else clause is executed, and they're not allowed in.

#!/bin/bash

customer_age=25

if [ $customer_age -ge 21 ]

echo "Come on in."

echo "You can't come in."

Copy the script from above into an editor, save it as a file called "if-age.sh", and use the chmod command  to make it executable. You'll need to do that with each of the scripts we discuss.

chmod +x if-age.sh

Let's run our script.

./if-age.sh

Now we'll edit the file and use an age less than 21.

customer_age=18

Make that change to your script, and save your changes. If we run it now the condition returns false, and the else clause is executed.

The elif clause adds additional conditional tests. You can have as many elif clauses as you like. They're evaluated in turn until one of them is found to be true. If none of the elif conditional tests prove to be true, the else clause, if present, is executed.

This script asks for a number then tells you if it is odd or even.  Zero is an even number , so we don't need to test anything.

All other numbers are tested by finding the modulo of a division by two. In our case, the modulo is the fractional part of the result of a division by two. If there is no fractional part, the number is divisible by two, exactly. Therefore it is an even number.

echo -n "Enter a number: "

read number

if [ $number -eq 0 ]

echo "You entered zero. Zero is an even number."

elif [ $(($number % 2)) -eq 0 ]

echo "You entered $number. It is an even number."

echo "You entered $number. It is an odd number."

To run this script, copy it to an editor and save it as "if-even.sh", then use chmod to make it executable.

Let's run the script a few times and check its output.

./if-even.sh

That's all working fine.

The brackets "  []  " we've used for our conditional tests are a shorthand way of calling the test program. Because of that, all the comparisons and tests that test supports are available to your if statement.

This is  just a few of them :

  • ! expression : True if the expression is false.
  • -n string : True if the length of the string is greater than zero.
  • -z string : True if the length of the string is zero. That is, it's an empty string.
  • string1 = string2 : True if string1 is the same as string2.
  • string1 != string2 : True if string1 is not the same as string2.
  • integer1 -eq integer2 : True if integer1 is numerically equal to integer2
  • integer1 -qt integer2 : True if integer1 is numerically greater than integer2
  • integer1 -lt integer2 : True if integer1 is numerically less than integer2
  • -d directory : True if the directory exists.
  • -e file : True if the file exists.
  • -s file : True if the file exists with a size of more than zero.
  • -r file : True if the file exists and the read permission is set.
  • -w file : True if the file exists and the write permission is set.
  • -x file : True if the file exists and the execute permission is set.

In the table, "file" and "directory" can include directory paths, either relative or absolute.

The equals sign " = " and the equality test -eq are not the same. The equals sign performs a character by character text comparison. The equality test performs a numerical comparison.

We can see this by using the test program on the command line.

test "this string" = "this string"

test "this string" = "that string"

test 1 = 001

test 1 -eq 001

In each case, we use the echo command  to print the return code of the last command. Zero means true, one means false.

Using the equals sign " = " gives us a false response comparing 1 to 001. That's correct, because they're two different strings of characters. Numerically they're the same value---one---so the -eq operator returns a true response.

If you want to use wildcard matching in your conditional test, use the double bracket " [[ ]] " syntax.

if [[ $USER == *ve ]]

  echo "Hello $USER"

  echo "$USER does not end in 've'"

This script checks the current user's account name. If it ends in " ve ", it prints the user name. If it doesn't end in " ve ", the script tells you so, and ends.

./if-wild.sh

You can put an if statement inside another if statement.

This is perfectly acceptable, but nesting if statements makes for code that is less easy to read, and more difficult to maintain. If you find yourself nesting more than two or three levels of if statements, you probably need to reorganize the logic of your script.

Here's a script that gets the day as a number, from one to seven. One is Monday, seven is Sunday.

It tells us a shop's opening hours. If it is a weekday or Saturday, it reports the shop is open. If it is a Sunday, it reports that the shop is closed.

If the shop is open, the nested if statement makes a second test. If the day is Wednesday, it tells us it is open in the morning only.

# get the day as a number 1..7

day=$(date +"%u")

if [ $day -le 6 ]

## the shop is open

if [ $day -eq 3 ]

# Wednesday is half-day

echo "On Wednesdays we open in the morning only."

# regular week days and Saturday

echo "We're open all day."

# not open on Sundays

echo "It's Sunday, we're closed."

Copy this script into an editor, save it as a file called "if-shop.sh", and make it executable using the chmod command.

We ran the script once and then changed the computer's clock to be a Wednesday, and re-ran the script. We then changed the day to a Sunday and ran it once more.

./if-shop.sh

Related: How to Use Double Bracket Conditional Tests in Linux

Conditional execution is what brings power to programming and scripting, and the humble if statement might well be the most commonly used way of switching the path of execution within code. But that doesn't mean it's always the answer.

Writing good code means knowing what options you have and which are the best ones to use in order to solve a particular requirement. The if statement is great, but don't let it be the only tool in your bag. In particular, check out the case statement which can be a solution in some scenarios.

Related: How to Use Case Statements in Bash Scripts

LinuxSimply

Home > Bash Scripting Tutorial > Bash Variables > Variable Declaration and Assignment > How to Assign Variable in Bash Script? [8 Practical Cases]

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

Mohammad Shah Miran

Variables allow you to store and manipulate data within your script, making it easier to organize and access information. 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 . As the Bash script offers a range of methods for assigning variables, I will thoroughly delve into each one.

Key Takeaways

  • Getting Familiar With Different Types Of Variables.
  • Learning how to assign single or multiple bash variables.
  • Understanding the arithmetic operation in Bash Scripting.

Free Downloads

Local vs global variable assignment.

In programming, variables are used to store and manipulate data. There are two main types of variable assignments: local and global .

A. Local Variable Assignment

In programming, a local variable assignment refers to the process of declaring and assigning a variable within a specific scope, such as a function or a block of code. Local variables are temporary and have limited visibility, meaning they can only be accessed within the scope in which they are defined.

Here are some key characteristics of local variable assignment:

  • Local variables in bash are created within a function or a block of code.
  • By default, variables declared within a function are local to that function.
  • They are not accessible outside the function or block in which they are defined.
  • Local variables typically store temporary or intermediate values within a specific context.

Here is an example in Bash script.

In this example, the variable x is a local variable within the scope of the my_function function. It can be accessed and used within the function, but accessing it outside the function will result in an error because the variable is not defined in the outer scope.

B. Global Variable Assignment

In Bash scripting, global variables are accessible throughout the entire script, regardless of the scope in which they are declared. Global variables can be accessed and modified from any script part, including within functions.

Here are some key characteristics of global variable assignment:

  • Global variables in bash are declared outside of any function or block.
  • They are accessible throughout the entire script.
  • Any variable declared outside of a function or block is considered global by default.
  • Global variables can be accessed and modified from any script part, including within functions.

Here is an example in Bash script given in the context of a global variable .

It’s important to note that in bash, variable assignment without the local keyword within a function will create a global variable even if there is a global variable with the same name. To ensure local scope within a function , using the local keyword explicitly is recommended.

Additionally, it’s worth mentioning that subprocesses spawned by a bash script, such as commands executed with $(…) or backticks , create their own separate environments, and variables assigned within those subprocesses are not accessible in the parent script .

8 Different Cases to Assign Variables in Bash Script

In Bash scripting , there are various cases or scenarios in which you may need to assign variables. Here are some common cases I have described below. These examples cover various scenarios, such as assigning single variables , multiple variable assignments in a single line , extracting values from command-line arguments , obtaining input from the user , utilizing environmental variables, etc . So let’s start.

Case 01: Single Variable Assignment

To assign a value to a single variable in Bash script , you can use the following syntax:

However, replace the variable with the name of the variable you want to assign, and the value with the desired value you want to assign to that variable.

To assign a single value to a variable in Bash , you can go in the following manner:

Steps to Follow >

❶ At first, launch an Ubuntu Terminal .

❷ Write the following command to open a file in Nano :

  • nano : Opens a file in the Nano text editor.
  • single_variable.sh : Name of the file.

❸ Copy the script mentioned below:

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. Next, variable var_int contains an integer value of 23 and displays with the echo command .

❹ Press CTRL+O and ENTER to save the file; CTRL+X to exit.

❺ Use the following command to make the file executable :

  • chmod : changes the permissions of files and directories.
  • u+x : Here, u refers to the “ user ” or the owner of the file and +x specifies the permission being added, in this case, the “ execute ” permission. When u+x is added to the file permissions, it grants the user ( owner ) permission to execute ( run ) the file.
  • single_variable.sh : File name to which the permissions are being applied.

❻ Run the script by using the following command:

Single Variable Assignment

Case 02: Multi-Variable Assignment in a Single Line of a Bash Script

Multi-variable assignment in a single line is a concise and efficient way of assigning values to multiple variables simultaneously in Bash scripts . This method helps reduce the number of lines of code and can enhance readability in certain scenarios. Here’s an example of a multi-variable assignment in a single line.

You can follow the steps of Case 01 , to save & make the script executable.

Script (multi_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. Then, three variables x , y , and z are assigned values 1 , 2 , and 3 , respectively. The echo statements are used to print the values of each variable. Following that, two variables var1 and var2 are assigned values “ Hello ” and “ World “, respectively. The semicolon (;) separates the assignment statements within a single line. The echo statement prints the values of both variables with a space in between. Lastly, the read command is used to assign values to var3 and var4. The <<< syntax is known as a here-string , which allows the string “ Hello LinuxSimply ” to be passed as input to the read command . The input string is split into words, and the first word is assigned to var3 , while the remaining words are assigned to var4 . Finally, the echo statement displays the values of both variables.

Multi-Variable Assignment in a Single Line of a Bash Script

Case 03: Assigning Variables From Command-Line Arguments

In Bash , you can assign variables from command-line arguments using special variables known as positional parameters . Here is a sample code demonstrated below.

Script (var_as_argument.sh) >

The provided Bash script starts with the shebang ( #!/bin/bash ) to use Bash shell. The script assigns the first command-line argument to the variable name , the second argument to age , and the third argument to city . The positional parameters $1 , $2 , and $3 , which represent the values passed as command-line arguments when executing the script. Then, the script uses echo statements to display the values of the assigned variables.

Assigning Variables from Command-Line Arguments

Case 04: Assign Value From Environmental Bash Variable

In Bash , you can also assign the value of an Environmental Variable to a variable. To accomplish the task you can use the following syntax :

However, make sure to replace ENV_VARIABLE_NAME with the actual name of the environment variable you want to assign. Here is a sample code that has been provided for your perusal.

Script (env_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The value of the USER environment variable, which represents the current username, is assigned to the Bash variable username. Then the output is displayed using the echo command.

Assign Value from Environmental Bash Variable

Case 05: Default Value Assignment

In Bash , you can assign default values to variables using the ${variable:-default} syntax . Note that this default value assignment does not change the original value of the variable; it only assigns a default value if the variable is empty or unset . Here’s a script to learn how it works.

Script (default_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The next line stores a null string to the variable . The ${ variable:-Softeko } expression checks if the variable is unset or empty. As the variable is empty, it assigns the default value ( Softeko in this case) to the variable . In the second portion of the code, the LinuxSimply string is stored as a variable. Then the assigned variable is printed using the echo command .

Default Value Assignment

Case 06: Assigning Value by Taking Input From the User

In Bash , you can assign a value from the user by using the read command. Remember we have used this command in Case 2 . Apart from assigning value in a single line, the read command allows you to prompt the user for input and assign it to a variable. Here’s an example given below.

Script (user_variable.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The read command is used to read the input from the user and assign it to the name variable . The user is prompted with the message “ Enter your name: “, and the value they enter is stored in the name variable. Finally, the script displays a message using the entered value.

Assigning Value by Taking Input from the User

Case 07: Using the “let” Command for Variable Assignment

In Bash , the let command can be used for arithmetic operations and variable assignment. When using let for variable assignment, it allows you to perform arithmetic operations and assign the result to a variable .

Script (let_var_assign.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. then the let command performs arithmetic operations and assigns the results to variables num. Later, the echo command has been used to display the value stored in the num variable.

Using the let Command for Variable Assignment

Case 08: Assigning Shell Command Output to a Variable

Lastly, you can assign the output of a shell command to a variable using command substitution . There are two common ways to achieve this: using backticks ( “) or using the $()   syntax. Note that $() syntax is generally preferable over backticks as it provides better readability and nesting capability, and it avoids some issues with quoting. Here’s an example that I have provided using both cases.

Script (shell_command_var.sh) >

The first line #!/bin/bash specifies the interpreter to use ( /bin/bash ) for executing the script. The output of the ls -l command (which lists the contents of the current directory in long format) allocates to the variable output1 using backticks . Similarly, the output of the date command (which displays the current date and time) is assigned to the variable output2 using the $() syntax . The echo command displays both output1 and output2 .

Assigning Shell Command Output to a Variable

Assignment on Assigning Variables in Bash Scripts

Finally, I have provided two assignments based on today’s discussion. Don’t forget to check this out.

  • Difference: ?
  • Quotient: ?
  • Remainder: ?
  • Write a Bash script to find and display the name of the largest file using variables in a specified directory.

In conclusion, assigning variable Bash is a crucial aspect of scripting, allowing developers to store and manipulate data efficiently. This article explored several cases to assign variables in Bash, including single-variable assignments , multi-variable assignments in a single line , assigning values from environmental variables, and so on. Each case has its advantages and limitations, and the choice depends on the specific needs of the script or program. However, if you have any questions regarding this article, feel free to comment below. I will get back to you soon. Thank You!

People Also Ask

Related Articles

  • How to Declare Variable in Bash Scripts? [5 Practical Cases]
  • Bash Variable Naming Conventions in Shell Script [6 Rules]
  • How to Check Variable Value Using Bash Scripts? [5 Cases]
  • How to Use Default Value in Bash Scripts? [2 Methods]
  • How to Use Set – $Variable in Bash Scripts? [2 Examples]
  • How to Read Environment Variables in Bash Script? [2 Methods]
  • How to Export Environment Variables with Bash? [4 Examples]

<< Go Back to Variable Declaration and Assignment  | Bash Variables | Bash Scripting Tutorial

icon linux

Mohammad Shah Miran

Hey, I'm Mohammad Shah Miran, previously worked as a VBA and Excel Content Developer at SOFTEKO, and for now working as a Linux Content Developer Executive in LinuxSimply Project. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). As a part of my job, i communicate with Linux operating system, without letting the GUI to intervene and try to pass it to our audience.

Leave a Comment Cancel reply

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

IMAGES

  1. Bash Conditional Statements

    bash conditional variable assignment

  2. Bash Conditional Statements

    bash conditional variable assignment

  3. Bash conditional statement

    bash conditional variable assignment

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

    bash conditional variable assignment

  5. Bash Function & How to Use It {Variables, Arguments, Return}

    bash conditional variable assignment

  6. Bash Scripting: Conditional If & The Test Command

    bash conditional variable assignment

VIDEO

  1. Working with BASH shell

  2. 6 storing values in variable, assignment statement

  3. && and || Linux Bash command chaining operators

  4. Conditional and selected signal assignment statements

  5. How to use Conditional Statements on Bash Script

  6. Bash If Statement

COMMENTS

  1. How to build a conditional assignment in bash?

    90. If you want a way to define defaults in a shell script, use code like this: : ${VAR:="default"} Yes, the line begins with ':'. I use this in shell scripts so I can override variables in ENV, or use the default. This is related because this is my most common use case for that kind of logic. ;]

  2. bash

    If your assignment is numeric, you can use bash ternary operation: (( assign_condition ? value_when_true : value_when_false )) Share. Improve this answer. ... Can we use "${a:-b}" for variable assignment in bash, with "a" a command? 2. bash: determining whether a variable specifically exists in the environment? 0.

  3. Bash Conditional Expressions (Bash Reference Manual)

    6.4 Bash Conditional Expressions. Conditional expressions are used by the [[ compound command (see Conditional Constructs ) and the test and [ builtin commands (see Bourne Shell Builtins ). The test and [ commands determine their behavior based on the number of arguments; see the descriptions of those commands for any other command-specific ...

  4. shell script

    but rather in a single conditional expression that is equivalent to a multi-statement if ... but also in the one for bash. shell-script; zsh; Share. Improve this question. Follow asked Feb 9, 2014 at 17:11. kjo kjo. 15.4k 25 25 gold badges 73 73 silver badges 114 114 ... for loop variable assignment with whitespaces. 2. export bash function ...

  5. How to Work with Variables in Bash

    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.

  6. Bash's conditional operator and assignment

    The importance of this type-checking lies in the operator's most common use—in conditional assignment statements. In this usage it appears as an expression on the right side of an assignment statement, as follows: variable = condition ? value_if_true : value_if_false

  7. Using Conditionals in Bash

    Bash conditionals let you write code that performs different tasks based on specified checks. These checks can be based on a simple assessment that results in a true or false result. Alternatively, a conditional may be in the form of a multiple case check where a number of values are assessed before an operation is performed.

  8. Conditional Constructs (Bash Reference Manual)

    Return a status of 0 or 1 depending on the evaluation of the conditional expression expression.Expressions are composed of the primaries described below in Bash Conditional Expressions.The words between the [[and ]] do not undergo word splitting and filename expansion. The shell performs tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process ...

  9. Conditional Assignment in Bash

    Bash. Many programming languages include an quick way to perform a conditional assignment. That is, assigning a variable with a value based on some condition. Normally this is done through a ternary operator. For example, here is how to write it in Javascript. age = 16; ageType = (age > 18) "Adult": "Child"; The variable ageType is dependent ...

  10. bash

    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. -

  11. How to Use Bash If Statements (With 4 Examples)

    Copy the script from above into an editor, save it as a file called "if-age.sh", and use the chmod command to make it executable. You'll need to do that with each of the scripts we discuss. chmod +x if-age.sh. Let's run our script. ./if-age.sh. Now we'll edit the file and use an age less than 21. customer_age=18.

  12. 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.

  13. Bash Scripting: Conditionals

    A conditional in Bash scripting is made up of two things: a conditional statement and one or more conditional operators. Bash scripts give us two options for writing conditional statements. We can either use an if statement or a case statement.In some situations, a nested if statement can also be helpful. These conditional statements only work by using operators.

  14. Unix Bash

    Putting the if statement in the assignment is rather clumsy and easy to get wrong. The more standard way to do this is to put the assignment inside the if:. if [ 2 = 2 ]; then mathstester="equal" else mathstester="not equal" fi

  15. Bash Variables And Conditionals

    And "$@" is the variable name for all arguments passed in. So we can reference "$1" to get the user's input and store it in a variable named "BIRTHDATE". #!/bin/bashBIRTHDATE=$1. Variables in bash can be assigned by using the below syntax. Note that there are no spaces around the "="! VARIABLE_NAME=VARIABLE_VALUE.

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

    The first line #!/bin/bash specifies the interpreter to use (/bin/bash) for executing the script.Then, three variables x, y, and z are assigned values 1, 2, and 3, respectively.The echo statements are used to print the values of each variable.Following that, two variables var1 and var2 are assigned values "Hello" and "World", respectively.The semicolon (;) separates the assignment ...

  17. How to Use the Ternary Conditional Operator in Bash

    $ a=1; b=2; c=3 $ echo $(( max = a > b ? ( a > c ? a : c) : (b > c ? b : c) )) 3. In this case, the second and third operands or the main ternary expression are themselves ternary expressions.If a is greater than b, then a is compared to c and the larger of the two is returned. Otherwise, b is compared to c and the larger is returned. Numerically, since the first operand evaluates to zero ...

  18. Bash conditional assignment that tests a variable whilst building a

    I found this question for how to do conditional assignment in bash, but what I'm trying to do is a little more complex, and I can't seem to get the syntax right. The condition in my case is to test a variable to see if it exists, and the output is concatenated to a string. Here's what I have so far:

  19. Set variable conditionally on command line [duplicate]

    I want to set a variable if my condition is true on my Ubuntu system. This proves that my if-statement is correct: $ (if [ 1 == 1 ]; then echo "hi there"; fi); hi there This proves that I can set . ... Setting environment variables with .bash_profile: only last export works properly. 1.