How to Use the Ternary Conditional Operator in Bash

Last updated: March 18, 2024

bash ternary operator assignment

1. Overview

One of the most useful features of Bash is its support for conditional statements. Among these is the ternary operator or conditional operator , denoted by the ?  symbol. The ternary operator returns different values based on the evaluation of a condition.

In this tutorial, we’ll discuss how to use the ternary operator in Bash. Further, we’ll look at equivalent constructs that use logical operators or if-else statements.

2. Ternary Operator

The ternary operator is a compact and efficient way to write conditional expressions . It’s a shorthand way of writing an if-else statement that returns a value.

In Bash, the syntax for the ternary operator occurs inside double parentheses which allow for arithmetic evaluation :

We’ll refer to the three operands respectively as expressions expr1 , expr2 , and expr3 :

The expression expr1 is first evaluated. If the result in Boolean is non-zero (true), then the interpreter evaluates expression expr2 . Otherwise, it evaluates expr3 .

3. Finding the Maximum Among Two Integers

Suppose we want to find the maximum of two integers a and b . We can either use a ternary expression to do so or use an equivalent construct via an if-else statement or logical operators.

3.1. Using a Ternary Expression

First, let’s see how we can set z to the maximum of a and b via a ternary expression:

Here, the interpreter evaluates the first operand and determines that it’s false since a ( 1 ) isn’t greater than b ( 2 ). Therefore, the returned value is the third operand,  b , which has a value of 2.

Alternatively, we can set the variable z directly within the double parentheses:

Instead of using double parentheses for arithmetic evaluation, we can also assign the result of a ternary expression to a variable using the let command:

Finally, it’s also possible to place the assignment inside the quotations:

Moreover, ternary expressions can generally be rewritten as if-else statements or using logical operators.

3.2. Equivalent if-else Statement

Let’s rewrite the ternary expression as an if-else statement:

We use square brackets to test an expression. The -gt option inside the brackets stands for greater than , i.e., we’re testing if the value of a is greater than b .

3.3. Equivalent Expression Using Logical Operators

Alternatively, we can use logical operators && and || to rewrite our expression:

The entire expression in this case runs in a subshell .

However, we can further shorten the expression:

This way, we don’t need to spawn a subshell for the assignment.

4. Ternary Expressions and Arithmetic Evaluation

It’s important to note that Bash’s ternary expressions are limited to arithmetic expressions only . However, we can always find a workaround by adding a subsequent if-else statement:

In this example, we’re using the ternary operator in combination with the modulo operator, % , to test whether the value of the variable x is even or odd. If the remainder of x is zero when divided by 2 , the ternary operator returns the value 1 . Otherwise, it returns 0 .

Then, we use an if-else statement to check the value of output and print the appropriate message, which we wouldn’t be able to do with the ternary expression alone.

5. Nested Ternary Expressions

It’s also possible to nest ternary expressions . For example, we can construct a ternary expression to find the maximum among three integers a , b , and c :

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 (false), the interpreter evaluates the third operand and returns the value of c since b isn’t greater than c .

6. Order of Evaluation

The ternary operator associates from right to left :

We can make the expression clearer by enclosing the third operand with single parentheses:

The two expressions are equivalent, though the second is more readable than the first. In cases where expressions could be misinterpreted, it’s good practice to highlight operands with parentheses for better readability .

As an example, suppose we wish to compare two integers a and b . If a is larger than b , then a is returned, otherwise, the larger of integers b and c is returned:

Since ternary expressions associate from right to left, we can highlight this fact:

Since expr1 is false, expr3 is evaluated and the result is the value of c .

7. Conclusion

In this article, we’ve seen that conditional operators can simplify code and make it more compact. If used wisely, conditional operators can also make code easier to read and understand. We’ve also seen that we can construct equivalent expressions using if-else statements or logical operators.

LinuxSimply

Home > Bash Scripting Tutorial > Bash Operator > Usage of Ternary Operator in Bash [with 2 Examples]

Usage of Ternary Operator in Bash [with 2 Examples]

Mohammad Shah Miran

A ternary operator is a concise way to express a conditional (if-else) statement in Bash. It’s called “ternary” because it involves three parts: a condition, an expression to evaluate if the condition is true, and an expression to evaluate if the condition is false. The Bash ternary operator, denoted by the ? : symbol . It allows the program to make decisions based on a condition and execute different code blocks accordingly.

In this guide, I’m going to show you how to use the ‘ternary’ operator in bash. So let’s start!

What is Ternary Operator in Bash Script?

The ternary operator in bash is a shorthand for if-else statements that return a value.

The common syntax it follows in Bash is:

Here, the condition is the expression that is to be evaluated. If the condition is true (zero), then the value will be returned. Otherwise, the value is set to false (one).

It is important to note that, the ternary operator in bash is only limited to the arithmetic expression of the bash script. The operator will return only 0 if the condition is true or 1 otherwise. To make the code more resourceful you can employ the if-else statement along with the ternary operator.

How to Use the Ternary Conditional Operator in Bash Script?

Let’s say you have two numbers, a and b , and you want to figure out the maximum value among them. To find the maximum value among two numbers, you can directly use the ternary operator syntax as follows:

This script prompts the user to input two numbers, ‘a’ and ‘b’, using the read -p command. It then employs the Bash ternary operator to compare ‘a’ and ‘b’. If ‘a’ is greater than ‘b’, it assigns the value of ‘a’ to the variable ‘z’. If ‘a’ is not greater than ‘b’, it assigns the value of ‘b’ to ‘z’. Finally, the script displays the maximum number among the two given numbers using the echo command .

How to Use the Ternary Conditional Operator in Bash Script

Alternatively, you can also define the variable z inside the double parentheses :

It is possible to use the let command instead of double parentheses when performing arithmetic evaluation. For example, you can use the let command to attribute the result of ternary expressions to a variable:

Finally, the assignment can also be placed within quotations :

2 Examples of Ternary Operator in Bash Scripting

In the following section, I will dive into two different examples of using ternary operator in bash scripting.

Example 1: Ternary Operator in Arithmetic Evaluation

Arithmetic evaluation is a powerful feature that allows user to perform mathematical operations directly within the scripts. The double parentheses ((…)) are commonly used to denote arithmetic evaluation. Within these parentheses, you can utilize the ternary operator to evaluate arithmetic expressions . As Bash’s ternary expression is only for arithmetic expression , it can’t accept any string value. The following script shows an example of its usage:

This bash script will ask the user to enter a number and store it in x. Then, it’ll use a modulus operation x% 2 == 0 to check if the remainder of x divided by 2 is 0. If it’s true, 1 will be assigned to ‘output’. Otherwise, 0 will be assigned to the ‘output’ variable. After that, it’ll use the ‘if-else’ condition to check the ‘output’ variable. If ‘output’ equals ‘1’, it’ll show “The number is Even”. Otherwise, it’ll print “Number is odd”.

Ternary Operator in Arithmetic Evaluation

Example 2: Nested Ternary Expressions to Compare Integer Number

An expression that is inside another expression is called a nested expression . Similarly, ternary expressions can also be nested by placing another ternary operator within the true or false branch of an outer ternary operator.

For instance, the nested ternary operator can be used to figure out the maximum value of three different numbers in a certain way.

In the above script, the ternary operator is structured to compare a with b and c . If a is greater than b , it then compares a with c . If a is the largest, it assigns a as the maximum. Otherwise, it evaluates b against c and assigns the largest of the two as the maximum. The result is stored in the variable ‘ max ‘. Finally, the script displays the maximum value among a , b , and c using the echo command .

Nested Ternary Expressions to Compare Integer Numbers

Order of Ternary Operator Evaluation

The order of ternary operator evaluation proceeds sequentially from right to left . The rightmost condition or operation is evaluated first, followed by subsequent expressions or conditions. For example, in (( expr1 ? expr2 : expr3 ? expr4 : expr5 )) , the expr3 will be evaluated first. If expr3 is true, expr4 is evaluated, and if expr3 is false, expr5 will be returned. Next, if expr1 is true the expr2 will be the final result, if false the output of the expr3 ? expr4 : expr5 will be returned.

Let’s see an example of comparing three integers to find the maximum value among them and learn the order of evaluation of the ternary operator in bash:

First, the expression compares var2 with var3 . If var2 is greater than var3 , it returns var2 as a greater value, var3 otherwise. Then the code evaluates whether var1 is greater or var2 . If the result is true, the code assigns var1 to var , if not it will assign the result of var2 > var3 ? var2 : var3 to the var variable .

Order of Ternary Operator Evaluation in bash

The ternary operator is a powerful tool that can be used to write more concise and readable Bash code. If you use them correctly, they can also make your code easier to read. However, it can also be confusing, especially for new Bash users. If you are new to Bash, I recommend that you start by using if-else statements and then move on to the ternary operator once you are more comfortable with Bash programming. Still, if you have any questions or queries related to ternary operator in Bash , feel free to comment below. Thank You!

People Also Ask

What is the ternary operator in a variable declaration.

The ternary operator is a compact statement used to assign value to a variable according to a condition. It is denoted by ?: and used in various programming languages for concise conditional assignments. The ternary operator is used in the following way: variable = (condition ? value_if_true : value_if_false);

Is ternary operator an expression?

Yes , ternary operator is an expression. The ternary operator evaluates to a value based on the condition provided. It is a short-term expression for a conditional statement. It is a compact and powerful way to make decisions within code.

Is ternary operator a binary operator?

A ternary operator is a non-binary operator . It is referred to as a ternary because it takes three arguments (condition, value if true, and value if false). This makes it different from traditional binary operators and adds to its conditional nature. The condition is represented as condition?value_if_true:value_if_false

Is the ternary operator faster than if-else?

In most cases, the speed difference is really small and depends on the language you’re using. But the fact that the operator is compact makes it look like it’s faster. This could make it easier to optimize your code and make it easier to read, especially if you’re using a language that has a good implementation of it. In some cases, the compiler or interpreter could make the operator faster than an if statement, so you might think it’s faster.

How do you assign a value to a ternary operator?

In bash programming languages, you assign a value to a ternary operator by using it within an expression. The format generally follows the syntax: variable = (condition ? value_if_true : value_if_false);

Here, the condition is evaluated. If true , value_if_true is assigned to the variable; if false , value_if_false is assigned. This statement provides a concise way to conditionally assign a value to a variable based on a particular condition.

How many ternary operators are there?

The ternary operator is usually considered to be a single operator , but it can also be used more than once in one expression. In the context of programming, it is often referred to as the conditional operator (ternary), which is a simple operator that takes 3 operands to decide on a condition.

Related Articles

  • Arithmetic Operators in Bash
  • Bash Logical Operators
  • Unary Operators in Bash
  • Bitwise Operators in Bash Scripting
  • An Overview of Bash Comparison [Conditional] Operators

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.

Ternary Operations in Bash: A Definitive Guide

Bash, the popular Unix shell scripting language, does not provide a direct implementation of the ternary operator ( ? : ). However, there are several alternative methods that can mimic its functionality. In this article, we'll explore the solutions to the following question:

Is there a way to do something like this using Bash? int a = (b == 5 ) ? c : d;

Using && and ||

Using a command substitution, using parameter expansion (for checking if a variable is set), using if and else.

Note: The cond && op1 || op2 expression has an inherent bug: if op1 has a nonzero exit status, op2 silently becomes the result. That expression is only safe to use if op1 can never fail.

Using Arithmetic Evaluation

Each of these methods has its pros and cons. The best method depends on your specific use case and personal preferences. It's essential to follow best practices, such as using quotes, double square brackets, and considering error handling, to ensure your script runs smoothly and efficiently. With this guide at your disposal, you can effectively use ternary-like operations in your Bash scripts to improve code readability and simplify logic.

Ternary Operator in Bash Script

  • Linux Howtos

Ternary Operator in Bash Script

This article is a trivial guide to the conditional operator, also known as the ternary operator, in Bash script.

The ternary or conditional operator is usually used as an in-line replacement of the if..else statement. In most programming languages, it uses two symbols ? and : to make a conditional statement.

A common syntax for the ternary conditional operator:

Bash doesn’t have direct support for the conditional operator. However, this ternary operation can be achieved using the following conditional statement.

This expression is evaluated as if the conditional-expression is true , then the && operator will be operated, and the Result1 will be the answer. But if the conditional-expression is false , then the second logical operator || will run, and it will give Result2 as an answer.

Implement Ternary Operator in Bash Script

We have run the program twice from the output to get both results.

Muhammad Husnain avatar

Husnain is a professional Software Engineer and a researcher who loves to learn, build, write, and teach. Having worked various jobs in the IT industry, he especially enjoys finding ways to express complex ideas in simple ways through his content. In his free time, Husnain unwinds by thinking about tech fiction to solve problems around him.

Related Article - Bash Operator

  • How to Use Double and Single Pipes in Bash
  • How to Use the Mod Operator in Bash
  • How to Solve Unary Operator Expected Error in Bash
  • Logical OR Operator in Bash Script
  • The -ne Operator in Bash

Ternary Operator

Learn what the ternary operator is and how it works in Bash.

Ternary operator

The ternary operator is also known as the conditional operator and ternary if . It first appeared in the programming language ALGOL. The operator turned out to be convenient and many programmers liked it. The languages of the next generation, BCPL and C, inherited the ternary if. It later came to almost all modern languages, including C++, C#, Java, Python, PHP, and more. A ternary operator is a compact form of the if statement.

For example, let’s suppose that our script has the following if statement:

Here, the result variable is assigned the zero value if var is less than 10. Otherwise, result gets the value of var .

We can get the same behavior using the ternary operator. It looks like this:

Run the commands discussed in this lesson in the terminal below.

Get hands-on with 1200+ tech skills courses.

Dey Code

Ternary operator (?:) in Bash – Bash

Photo of author

Quick Fix: The ternary operator ? : is a shorthand for the if/then/else statement.

The Solutions:

Solution 1: using double braces.

The double braces syntax allows for concise conditional statements:

Solution 2: Using Case Statement

The case statement provides a more structured approach:

Solution 3: Using Logical Operators

Logical operators can also be used to achieve the same result:

Solution: Ternary operator (?:) in Bash

Bash doesn’t have a built-in ternary operator (?:) like C++, Java, or JavaScript. However, you can simulate it using command substitution and conditional execution.

The syntax is:

  • variable : the variable to store the result
  • condition : the condition to evaluate
  • value_if_true : the value to assign to variable if the condition is true
  • value_if_false : the value to assign to variable if the condition is false

For example:

Solution 3: Parameter Expansion

If the condition merely checks if a variable is set, there’s an even shorter form using Parameter Expansion:

This assigns to a the value of VAR if VAR is set, otherwise it assigns the default value 20 . The default value can also be an expression.

Solution 5: Ternary operator (?) in Bash

The ternary operator is implemented in Bash as the [[ ... ? ... : ... ]] syntax. The expression in the first position will be evaluated to a boolean value. If the expression is true, the second expression will be evaluated, otherwise the third expression will be evaluated. The result of the expression will be the result of the evaluated expression.

Make Terraform resource key multiline – Terraform

What is the maximum length of a URL in different browsers? – Url

© 2024 deycode.com

Next: Shell Arithmetic , Previous: Interactive Shells , Up: Bash Features   [ Contents ][ Index ]

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

Expressions may be unary or binary, and are formed from the following primaries. Unary expressions are often used to examine the status of a file. There are string operators and numeric comparison operators as well. Bash handles several filenames specially when they are used in expressions. If the operating system on which Bash is running provides these special files, Bash will use them; otherwise it will emulate them internally with this behavior: If the file argument to one of the primaries is of the form /dev/fd/ N , then file descriptor N is checked. If the file argument to one of the primaries is one of /dev/stdin , /dev/stdout , or /dev/stderr , file descriptor 0, 1, or 2, respectively, is checked.

When used with [[ , the ‘ < ’ and ‘ > ’ operators sort lexicographically using the current locale. The test command uses ASCII ordering.

Unless otherwise specified, primaries that operate on files follow symbolic links and operate on the target of the link, rather than the link itself.

True if file exists.

True if file exists and is a block special file.

True if file exists and is a character special file.

True if file exists and is a directory.

True if file exists and is a regular file.

True if file exists and its set-group-id bit is set.

True if file exists and is a symbolic link.

True if file exists and its "sticky" bit is set.

True if file exists and is a named pipe (FIFO).

True if file exists and is readable.

True if file exists and has a size greater than zero.

True if file descriptor fd is open and refers to a terminal.

True if file exists and its set-user-id bit is set.

True if file exists and is writable.

True if file exists and is executable.

True if file exists and is owned by the effective group id.

True if file exists and has been modified since it was last read.

True if file exists and is owned by the effective user id.

True if file exists and is a socket.

True if file1 and file2 refer to the same device and inode numbers.

True if file1 is newer (according to modification date) than file2 , or if file1 exists and file2 does not.

True if file1 is older than file2 , or if file2 exists and file1 does not.

True if the shell option optname is enabled. The list of options appears in the description of the -o option to the set builtin (see The Set Builtin ).

True if the shell variable varname is set (has been assigned a value).

True if the shell variable varname is set and is a name reference.

True if the length of string is zero.

True if the length of string is non-zero.

True if the strings are equal. When used with the [[ command, this performs pattern matching as described above (see Conditional Constructs ).

‘ = ’ should be used with the test command for POSIX conformance.

True if the strings are not equal.

True if string1 sorts before string2 lexicographically.

True if string1 sorts after string2 lexicographically.

OP is one of ‘ -eq ’, ‘ -ne ’, ‘ -lt ’, ‘ -le ’, ‘ -gt ’, or ‘ -ge ’. These arithmetic binary operators return true if arg1 is equal to, not equal to, less than, less than or equal to, greater than, or greater than or equal to arg2 , respectively. Arg1 and arg2 may be positive or negative integers. When used with the [[ command, Arg1 and Arg2 are evaluated as arithmetic expressions (see Shell Arithmetic ).

Bash - Ternary Operator

Bash or shell script example for Ternary Operator expression with examples.

Bash programming does not have support for ternary operator syntax.

Ternary operators are written in the Java language

The syntax is similar to the if and else conditional expression. if the expression is true, value1 is returned, else value2 is returned.

How to use ternary Operator in Bash

There are several ways we can write syntax in place of ternary operator syntax.

The first way, use if-else with expression syntax.

The second way, use Arithmetic expressions using && and || Syntax is

if the expression1 is true, Expression2 is evaluated, else Expression3 is evaluated

Here is an example program

There is another way in which we can assign variables instead of expressions.

using let we can assign variables based on condition expression result

Brandon Rozek

Photo of Brandon Rozek

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

Conditional Assignment in Bash

bash ternary operator 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 :

sysxplore

Operators in Bash Scripting

Traw

On this page

Operators allow you to perform operations on values and variables in Bash. Bash provides various types of operators for different purposes:

Arithmetic Operators

Assignment operators, relational operators, logical operators, bitwise operators, ternary operator.

This section will provide detailed information about each type of operator.

Arithmetic operators allow you to perform mathematical operations on integers. They combine integer variables and values to produce a new integer result.

Below is a list of all the arithmetic operators available in bash:

The addition, subtraction, multiplication, and division operators work as expected for mathematical operations.

The modulus (%) operator returns the remainder of the division between two integers. This is useful for checking if a number is even or odd, among other uses.

Assignment operators store values or the result of an expression into a variable.

Simple assignment allows storing values in a variable. The combined assignment operators like += and -= allow modifying variables more concisely. For instance, a+=b is the same as a = a + b.

Relational operators are used for comparing integers and strings to evaluate conditions.

-eq, -ne, -gt, -ge, -lt, and -le work on integers, while <, <=, >, and >= work on string sorting order. These are commonly used in if statements and loops to control program flow. The equal (==) and not equal (!=) operators are useful for comparing integers.

Logical operators are used for combining and negating conditional expressions.

The NOT operator (!) inverts a true condition to false or a false condition to true. The AND operator (&&) evaluates to true if both operands are true, while the OR operator (||) evaluates to true if either operand is true. These allow creating complex conditional logic in scripts.

Bitwise operators manipulate integers at the bit level.

Bitwise operators treat integers as binary strings and set, unset, or toggle bits at specific positions. This allows bitmasking, toggling, and shifting values for flags and low-level binary operations.

The ternary operator allows simple conditional expressions.

The ternary operator is structured as condition ? resultIfTrue : resultIfFalse . It tests the given condition and returns the specified result depending on whether the condition evaluated to true or false. This provides a concise way to assign values based on conditions.

Bash includes a set of operators such as arithmetic, relational, logical, bitwise, assignment, and ternary operators. These operators allow for mathematical computations, condition evaluations, expression combinations, bit manipulations, value assignments, and conditional ternary expressions within Bash scripts. Understanding these operators is essential for effective Bash scripting.

Quoting in Bash Scripting

You might also like

Bash bitwise operators

Bash bitwise operators

Subshells in Bash

Subshells in Bash

Indexed Arrays in Bash

Indexed Arrays in Bash

Getting Started with Bash Scripting

Getting Started with Bash Scripting

Subscribe to sysxplore newsletter and stay updated..

  • UPSC History Notes
  • UPSC Geography Notes
  • UPSC Polity Notes
  • UPSC Ethics Notes
  • UPSC Economics Notes
  • UPSC Science and Technology Notes
  • UPSC Govt. Schemes Notes
  • UPSC eligibility-criteria
  • UPSC Syllabus
  • UPSC Exam Pattern
  • UPSC Admit Card
  • UPSC Optional Subject
  • UPSC Prelims Syllabus
  • UPSC Main Exam Pattern
  • UPSC prelims-2024-exam-pattern
  • List of Waterfalls in Russia
  • List of Major Rivers in the Russia
  • Volcano Eruption
  • Top 10 Products Imported to Russia 2024
  • List of top 10 Countries of Cotton Production
  • List of Provinces of China and their Capitals
  • List of Top 10 Iron Ore-Producing Countries in the World
  • List of Countries Bordering Israel - Explained in Map
  • How Many Countries are there in the World? (Updated 2024)
  • World Migratory Bird Day 2023: Date, Theme & Facts
  • Russian Energy Sector - Oil, Gas, and Renewable Resources
  • Formation of Himalaya - Location with Details Explanation
  • Russian Relations with Neighboring Countries
  • Russian Foreign Policy - Relations with the United States, Europe, and Asia
  • Russia is in Which Continent? Asia or Europe?
  • List of Top 10 Pulses-Producing States in India
  • Migration Certificate - How to Apply, Validity & Importance
  • Highest Mountain Peaks in India
  • Nuclear Suppliers Group (NSG)

Moscow – Map, History, Geography & Population

Moscow, the capital of Russia, is a city full of history, culture, and different people. It’s been important for a long time and has changed the world a lot. From being the main place for the Russian Empire to being the capital of the biggest country today, Moscow has a really interesting story.

In this article, we’ll explore the city of Moscow, its geography, history, map, demography, population, etc.

Table of Content

Moscow – The Capital of Russia

Map of moscow, history of moscow, geography of moscow, population of moscow.

Moscow is the capital and largest city of Russia, situated on the Moskva River in the western part of the country. It has a rich history dating back over 800 years and is known for its iconic landmarks such as the Kremlin, Red Square, and St. Basil’s Cathedral. The city has a population of over 12 million people, making it one of the most populous cities in Europe. Moscow is a major political, economic, cultural, and scientific center with a diverse population and vibrant arts and entertainment scene.

Moscow’s map is a representation of its rich history and development over the centuries. The city’s layout is a combination of radial patterns, with main roads radiating out from the center, and circular patterns, with ring roads connecting different districts.

Map of Moscow

  • In the beginning, around the 12th century, Moscow started as a small settlement founded by Prince Yuri Dolgoruky. It grew due to its strategic location on trade routes.
  • During the 13th century, the Mongols invaded Moscow, ruling for over 200 years. In the 15th century, Ivan the Great expanded Moscow’s influence, becoming the first Tsar.
  • Moscow later became the capital in the 16th century, despite a brief move to St. Petersburg.
  • The Time of Troubles in the early 17th century brought instability, with Moscow facing invasions.
  • The Romanov dynasty restored stability, ruling for over 300 years and contributing to Moscow’s cultural and economic growth.
  • In 1917, the Bolsheviks overthrew the Romanovs, establishing the Soviet Union. Moscow became a key political and industrial hub.
  • During World War II, Moscow faced Nazi invasion but successfully resisted. In 1991, the Soviet Union collapsed, and Russia gained independence.
  • Moscow embraced capitalism, experiencing economic growth and cultural exchange. Today,
  • Moscow is a bustling global city with modern developments while preserving its historical landmarks.

Check : Russia | Area, Population, Climate, Government & Resources in Russia

The below describes the geography of Moscow in detail:

  • Moscow sits on the East European Plain, a vast flatland extending from Russia to Poland.
  • Coordinates: 55°45’N and 37°37’E.
  • Mostly flat with an average elevation of 156 meters.
  • Vorobyovy Gory (Sparrow Hills) is the highest point at 220 meters.
  • Divided by the Moskva River: northern part is flat, southern part has hills.
  • Abundance of parks, forests, and green spaces, making it one of Europe’s greenest cities.
  • Humid continental climate with long, cold winters and short, warm summers.
  • January averages -9°C (16°F), July averages 19°C (66°F).
  • Significant precipitation (707 mm annually) with common snowfall in winter.

Water Bodies

  • Moskva River is the main water body, 502 km long.
  • Several smaller rivers and canals feed into it.
  • Over 100 lakes, mostly artificial, serving various purposes.

Neighborhoods

  • Divided into 125 districts, each with a unique character.
  • Central part hosts iconic landmarks; north is industrial; south is residential; west is upscale; east is working-class.

Transportation

  • Extensive network includes trains, buses, trams, trolleybuses, and the famous Moscow Metro.
  • Moscow Metro is both transportation and a tourist attraction.
  • Five major railway terminals connect Moscow to other cities.
  • Airports like Sheremetyevo and Domodedovo serve millions annually.
  • Red Square, a UNESCO World Heritage Site, is central with St. Basil’s Cathedral and the Kremlin.
  • The Russian President’s official residence is the Kremlin.
  • Other landmarks include Bolshoi Theatre, Gorky Park, and Stalinist skyscrapers known as the Seven Sisters.
  • Economic hub with diverse industries – finance, commerce, manufacturing, and technology.
  • Headquarters of Russian and multinational companies.
  • Moscow International Business Center (Moscow-City) is a significant business district.

Green Spaces

  • Despite urban development, Moscow has over 100 parks, including Gorky Park and Tsaritsyno Park.
  • Botanical Garden of Moscow State University is a popular spot for nature lovers.

Surrounding Landscape

  • Central Federal District is surrounded by picturesque countryside.
  • The Golden Ring, ancient towns northeast of Moscow, is known for history and scenic beauty.
  • Tver Oblast region nearby has lakes and forests, offering natural retreats.

To begin with, let us first understand the current population of Moscow. As of 2021, the estimated population of Moscow is approximately 12.5 million people. This number includes not just the residents of the city but also those living in its surrounding areas.

  • Total Population: In 2021, Moscow had about 12.5 million people, making it the biggest city in Europe and the seventh biggest in the world. More folks keep moving in every year, about 0.7% more. People come to Moscow for jobs and opportunities from all over Russia and beyond.
  • Population Density: Moscow is pretty crowded compared to the rest of Russia. There are about 4,970 people for every square kilometer, way more than the national average of just 8 people per square kilometer. It’s because Moscow is a big city where lots of people live and work.
  • Age Distribution: People of all ages live in Moscow. The average age is about 40 years old, a bit higher than the national average. But there are many young folks too, about 21% are kids aged 0-14. That’s because Moscow has lots of schools and colleges, so it’s attractive to students. But there are also quite a few older folks, around 12% are 65 or older. Some of them retire in Moscow because it has good facilities for older people.
  • Gender Ratio: In Moscow, there are a bit more women than men, with 53% being female and 47% male. This is similar to the rest of Russia, where women are slightly more. But interestingly, among younger folks, there are almost equal numbers of boys and girls, especially among kids aged 0-14.

Also Read: Capital of Russia

Moscow Demographic Overview

The below table lists the demographic overview of Moscow:

Conclusion – Moscow

Moscow has been through a lot wars, revolutions, and big changes . But it’s still standing strong! Its long history, mix of people, and interesting location make it special. With famous places to visit and a lively culture, there’s always something to do in Moscow. It’s a big deal on the world stage, influencing Russia’s politics, economy, and culture.

People Also Read:

  • Education System of UAE : Universities and Institutions
  • Healthcare System in UAE: Services and Facilities
  • UAE National Day
  • International University in Moscow

Moscow – FAQs

What is the geography of moscow.

Moscow sits on the Moskva River, spanning over 500 km through central Russia. With 49 bridges, it’s near the border of the forest and forest-steppe zone.

What is the population of Moscow over time?

Moscow’s metro area population in 2023 was 12.68 million, up 0.31% from 2022. In 2022, it was 12.64 million, a 0.38% increase from 2021, which had 12.59 million, up 0.44% from 2020.

Is Moscow the capital of Russia?

Moscow, Russia’s capital along the Moskva River, is the largest city in the country with about 12 million people. It hosts the President’s seat, government, and State Duma (Parliament).

Where is Moscow located?

Moscow is located in Russia’s European region, roughly at latitude 55°45’N and longitude 37°37’E.

What is the history of Moscow?

The history of Moscow began when Prince Yuri Dolgoruky built the city in the twelfth century. With the passage of time and the advent of strongmen such as Ivan the Great, as well as Mongol invasions and times of political unrest, it has developed into an important political, economic, and cultural hub.

What is Moscow’s population?

Moscow is one of the most populated cities in Europe, with an estimated 12.5 million residents as per latest estimates.

What is special about Moscow?

Moscow’s stunning architecture, iconic landmarks, and bustling city life captivate visitors. From the Red Square to the Kremlin, there’s plenty to explore and discover.

Is Moscow a beautiful city?

Moscow, Russia’s capital, is celebrated for its rich history, stunning architecture, and vibrant cultural scene, earning it a place among the world’s most beautiful cities.

What is the geography of Moscow like?

Moscow is split in half by the Moskva River and is located on the East European Plain. Although there is some mountainous hills in the southern portion, the surface is generally level. The city has mild summers and frigid winters due to its humid continental climate.

Is Moscow a diverse city?

Yes, Moscow is a multicultural metropolis home to people of many nationalities, including Tatars, Russians, Ukrainians, Armenians, and others. Its cosmopolitan nature is further enhanced by the sizeable expatriate community that it houses.

What is the economy of Moscow like?

Russia’s economic center is Moscow, which is well-known for its wide range of sectors, including technology, industry, banking, and commerce. Numerous multinational enterprises and Russian companies have their headquarters in this city.

Please Login to comment...

Similar reads.

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Put-in tours

Original tour agency in moscow and st petersburg..

Onboard a Soviet van!

Welcome to Russia!

We are Sergey and Simon, a Russian and a Frenchman, both  passionate about Moscow, Saint-Petersburg and classic cars. Together, we have created Put-in tours. Our goal is to help you experience Russian culture off the beaten path. Join us onboard our classic Soviet van and let’s get rolling!

In Moscow we offer you a city tour to discover most of the city in an original way as well as a night tour to admire the lights. Our pubcrawl is ideal to explore Moscow’s night-life and have fun. If you are craving to discover Russian culture, come impress your senses during our monastery diner or join our 100% Russian Banya Excursion . The latest will also bring you to Sergiyev Posad and it’s famous monastery!

For the most extreme travellers, our shooting tour will deliver your daily dose of adrenaline whereas our tank excursion will let you ride a real tank and shoot a bazooka.

We also offer help to receive your visa , safe and multilingual airport transfers , as well as organisation services for team-building events or bachelor parties .

All our excursions (but the monastery diner) happen onboard our Soviet military vans and can be covered by our  professionnal photographer or videographer.

In Saint Petersburg

We welcome you in Saint Petersburg onboard our Soviet van to discover the imperial city with our city tour and night tour .

Continue your discovery in style! The adrenaline lovers will like our shooting tour  which brings 3 Russian weapons to the tip of your trigger finger.

Follow us on Social Media...

Our partners

© Copyright 2021 - Put-in tours Designed by SD Marketing & Design

At Put-in tours, we put you in our classic Soviet vans to go explore Moscow, Saint Petersburg and Russian culture off the beaten path. Discover our Moscow city guided tour, visit Moscow by night, join our banya & Sergiyev Posad excursion, visit and dine in one of Moscow's oldest monastery or even Luzhniki stadium, before you party on our famous pubcrawl! Original and atypical tours : Shoot AK47 and a bazooka after riding on a tank with our tank & bazooka excursion ! Extreme tours: Fly a fighter jet in Moscow onboard a L-29 or L-39 aircraft!

© Copyright 2021 – Put-in tours

Design web: SD Marketing & Design

Home About us Videos Moscow Saint-Petersburg Contact Online booking Blog Disclaimer Privacy Policy

WhatsApp us

IMAGES

  1. How to Use Ternary Operator (?:) in Bash

    bash ternary operator assignment

  2. How to Use Ternary Operator (?:) in Bash

    bash ternary operator assignment

  3. How to Use Ternary Operator (?:) in Bash

    bash ternary operator assignment

  4. Statements (if-else, case, ternary operators) || Complete Course

    bash ternary operator assignment

  5. Ternary Operator

    bash ternary operator assignment

  6. Usage of Ternary Operator in Bash [with 2 Examples]

    bash ternary operator assignment

VIDEO

  1. Working with BASH shell

  2. Program Operator Assignment

  3. Pemrograman Operator Assignment

  4. 6_Operator Assignment Relational LogicalBitwise

  5. operators in C||arithmetic operator||assignment operator||increment & decrement operator||part-1

  6. Ternary Operator in C Print Absolute Numbers

COMMENTS

  1. syntax

    Bash does have a ternary operator for integers and it works inside the arithmetic expression ((...)). See Shell Arithmetic. ... So, that expression is only safe to use if op1 can never fail (e.g., :, true if a builtin, or variable assignment without any operations that can fail (like division and OS calls)).

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

  3. Is there an inline-if with assignment (ternary conditional) in bash?

    Ternary operator (?:) in Bash. If this were AS3 or Java, I would do the following: fileName = dirName + "/" + (useDefault ? defaultName : customName) + ".txt"; But in shell, that seems needlessly complicated, requiring several lines of code, as well as quite a bit of repeated code.

  4. Usage of Ternary Operator in Bash [with 2 Examples]

    This script prompts the user to input two numbers, 'a' and 'b', using the read -p command. It then employs the Bash ternary operator to compare 'a' and 'b'. If 'a' is greater than 'b', it assigns the value of 'a' to the variable 'z'. If 'a' is not greater than 'b', it assigns the value of 'b' to 'z ...

  5. shell

    Can we use bash's conditional operator with assignment operators after colon? Bash reference manual explains the arithmetic operators as follows. ... As WP says, $(()) can only contain arithmetic expressions and therefore, a general ternary assignment doesn't exist in Bash. - zakmck. Apr 10, 2023 at 18:49. @zakmck i think you should check ...

  6. Ternary Operations in Bash: A Definitive Guide

    Bash, the popular Unix shell scripting language, does not provide a direct implementation of the ternary operator (? :). However, there are several alternative methods that can mimic its functionality. In this article, we'll explore the solutions to the following question: Is there a way to do something like this using Bash?

  7. bash

    A case statement is far more readable than jamming it all into one line (which can end in catastrophe if the second command can fail, in this case, it is fine, but getting into that habit can be costly).

  8. How to Use Ternary Operator (?:) in Bash

    In this case, the output will be 30. Code Execution. The code output can be seen by executing the bash script below: $ bash ternary_op.sh. Variable 'a' has a value of 10, variable 'b' has a value of 20, and variable 'c' has a value of 30. A variable c has the greatest value among the three, so its value will be printed on the terminal.

  9. Ternary Operator in Bash Script

    This article is a trivial guide to the conditional operator, also known as the ternary operator, in Bash script. Ternary Operator in Bash Script. The ternary or conditional operator is usually used as an in-line replacement of the if..else statement. In most programming languages, it uses two symbols ? and : to make a conditional statement.

  10. Ternary Operator

    The ternary operator is also known as the conditional operator and ternary if. It first appeared in the programming language ALGOL. The operator turned out to be convenient and many programmers liked it. The languages of the next generation, BCPL and C, inherited the ternary if. It later came to almost all modern languages, including C++, C# ...

  11. Ternary operator (?:) in Bash

    Bash doesn't have a built-in ternary operator (?:) like C++, Java, or JavaScript. However, you can simulate it using command substitution and conditional execution. The syntax is:

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

  13. How to use ternary operator in bash |shell script programming

    Bash programming does not have support for ternary operator syntax. Ternary operators are written in the Java language. expression?value1:value2 The syntax is similar to the if and else conditional expression. if the expression is true, value1 is returned, else value2 is returned. How to use ternary Operator in Bash. There are several ways we ...

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

  15. Operators in Bash Scripting

    Bash includes a set of operators such as arithmetic, relational, logical, bitwise, assignment, and ternary operators. These operators allow for mathematical computations, condition evaluations, expression combinations, bit manipulations, value assignments, and conditional ternary expressions within Bash scripts.

  16. How does the Conditional (ternary) Operator get evaluated?

    For the ternary operator the term "short circuit" can be used in a broader sense, as there is no left-to-right evaluation order as for the logical operators. The concept here is more precisely called "lazy evaluation". This simply means that, after evaluating the condition, only the matching "conclusion" part is evaluated.

  17. How to Find Largest Number using Ternary Operator in PHP?

    Given three different numbers, the task is to find the Largest Number using Ternary Operator in PHP. In PHP, the ternary operator (?:) allows you to make a quick decision based on a condition. It is a shorthand method to write an if…else statement. You can use the ternary operator to find the largest number among two or more numbers.

  18. List of International Airports in Russia

    This international airport has two runways. The airport served 24.01 million travelers in 2019. In 2021, Vnukovo ranked as the ninth busiest airport in Europe. Azimuth, Azur Air, Gazpromavia, I-Fly, Pobeda, RusLine, and Utair all use it as a hub. The elevation of Vnukovo is 204 meters above sea level.

  19. Moscow

    Moscow is the capital and largest city of Russia, situated on the Moskva River in the western part of the country. It has a rich history dating back over 800 years and is known for its iconic landmarks such as the Kremlin, Red Square, and St. Basil's Cathedral. The city has a population of over 12 million people, making it one of the most ...

  20. Libraries in Moscow

    It is a subdivision of Moscow State University - a self-governed state higher educational institution of the Russian Federation. The Library was founded in 1756. It is a scientific and a methodological centre for other higher institutions libraries functioning in Russia. Address: Mohovaya str. 9 | Phone: +7 (495) 203-2656.

  21. Bash one-liner using ternary expressions

    bash doesn't have a ternary operator. The precedence of a chain of && and || operators is not quite the same as in C; a && b || c will run b only if a succeeds, but a succeeds and b subsequently fails, c will run as well. -

  22. Tours in Moscow and St Petersburg

    Welcome to Russia! We are Sergey and Simon, a Russian and a Frenchman, both passionate about Moscow, Saint-Petersburg and classic cars. Together, we have created Put-in tours. Our goal is to help you experience Russian culture off the beaten path. Join us onboard our classic Soviet van and let's get rolling!