Linux and or operators

Unix / Linux — Shell Basic Operators

There are various operators supported by each shell. We will discuss in detail about Bourne shell (default shell) in this chapter.

We will now discuss the following operators −

  • Arithmetic Operators
  • Relational Operators
  • Boolean Operators
  • String Operators
  • File Test Operators

Bourne shell didn’t originally have any mechanism to perform simple arithmetic operations but it uses external programs, either awk or expr.

The following example shows how to add two numbers −

The above script will generate the following result −

The following points need to be considered while adding −

There must be spaces between operators and expressions. For example, 2+2 is not correct; it should be written as 2 + 2.

The complete expression should be enclosed between ‘ ‘, called the backtick.

Arithmetic Operators

The following arithmetic operators are supported by Bourne Shell.

Assume variable a holds 10 and variable b holds 20 then −

Operator Description Example
+ (Addition) Adds values on either side of the operator `expr $a + $b` will give 30
— (Subtraction) Subtracts right hand operand from left hand operand `expr $a — $b` will give -10
* (Multiplication) Multiplies values on either side of the operator `expr $a \* $b` will give 200
/ (Division) Divides left hand operand by right hand operand `expr $b / $a` will give 2
% (Modulus) Divides left hand operand by right hand operand and returns remainder `expr $b % $a` will give 0
= (Assignment) Assigns right operand in left operand a = $b would assign value of b into a
== (Equality) Compares two numbers, if both are same then returns true. [ $a == $b ] would return false.
!= (Not Equality) Compares two numbers, if both are different then returns true. [ $a != $b ] would return true.

It is very important to understand that all the conditional expressions should be inside square braces with spaces around them, for example [ $a == $b ] is correct whereas, [$a==$b] is incorrect.

All the arithmetical calculations are done using long integers.

Relational Operators

Bourne Shell supports the following relational operators that are specific to numeric values. These operators do not work for string values unless their value is numeric.

For example, following operators will work to check a relation between 10 and 20 as well as in between «10» and «20» but not in between «ten» and «twenty».

Assume variable a holds 10 and variable b holds 20 then −

Источник

6 операторов для цепочек командной строки оболочки Bash

Вступление

Теперь давайте обсудим каждый Оператор один за другим.

1. && Оператор (AND оператор)

Синтаксис использования оператора AND:

Читайте также:  Диспетчер устройств realtek hd windows 10

Оператор выполнит вторую команду только в том случае, если команда 1 успешно выполнена.

Теперь рассмотрим синтаксис выше.

Здесь команда 2 будет выполняться только в том случае, если команда 1 выполнена успешно. Например :

Здесь, как вы можете видеть ниже, первая команда успешно завершена, тогда выполняется вторая команда df -h.

Теперь давайте проверим оператор AND по-другому.

Здесь я не буду выполнять первую команду и посмотрю, выполняется ли вторая команда или нет.

Как вы можете видеть выше, первая команда не работает, поэтому вторая команда не выполняется.

2. OR Оператор (||)

Синтаксис использования оператора OR:

OR полностью противоположна оператору &&.

OR выполнит вторую команду только в том случае, если первая команда провалится.

Теперь давайте приведем пример:

Как вы можете видеть выше, вторая команда выполнена, то есть «df -h», когда первая команда не удалась.

3. Оператор AND & OR (&& и ||)

Комбинация оператора && и OR (||) довольно интересна и даст вам хороший результат, если вы используете его правильно.

Комбинация этих двух операторов, как например, if … else в программировании.

Давайте приведем пример, чтобы вы получили больше представлений по этому поводу:

Как вы можете видеть выше, наша первая команда успешно выполнена, поэтому мы можем получить требуемое сообщение.

4. Оператор PIPE (|)

PIPE – это своего рода оператор, который может использоваться для отображения вывода первой команды, принимая ввод второй команды.

Например, вы хотите проверить все текущие системные процессы, используя команду ps -ef. но поскольку список процессов настолько длинный, что его нельзя охватить на одном экране.

В этом случае вы можете использовать фильтр с командой more.

5. Оператор точка с запятой (;)

Оператор точка с запятой выполняет несколько команд одновременно последовательно, как упоминалось, и обеспечивает вывод без зависимости от успеха и отказа других команд, таких как && и OR (||).

Посмотрите пример ниже:

6. Амперсанд Оператор (&)

Оператор Амперсанда – это своего рода оператор, который выполняет заданные команды в фоновом режиме.

Вы можете использовать этот оператор для одновременного выполнения нескольких команд.

Вы также можете выполнять несколько команд с помощью оператора Ampersand. См. Команду ниже.

Источник

10 Useful Chaining Operators in Linux with Practical Examples

Chaining of Linux commands means, combining several commands and make them execute based upon the behaviour of operator used in between them. Chaining of commands in Linux, is something like you are writing short shell scripts at the shell itself, and executing them from the terminal directly. Chaining makes it possible to automate the process. Moreover, an unattended machine can function in a much systematic way with the help of chaining operators.

10 Chaining Operators in Linux

This Article aims at throwing light on frequently used command­-chaining operators, with short descriptions and corresponding examples which surely will increase your productivity and lets you write short and meaningful codes beside reducing system load, at times.

1. Ampersand Operator (&)

The function of ‘&‘ is to make the command run in background. Just type the command followed with a white space and ‘&‘. You can execute more than one command in the background, in a single go.

Run one command in the background:

Run two command in background, simultaneously:

2. semi-colon Operator (;)

The semi-colon operator makes it possible to run, several commands in a single go and the execution of command occurs sequentially.

Читайте также:  Windows loader by daz advanced option

The above command combination will first execute update instruction, then upgrade instruction and finally will create a ‘test‘ directory under the current working directory.

3. AND Operator (&&)

The AND Operator (&&) would execute the second command only, if the execution of first command SUCCEEDS, i.e., the exit status of the first command is 0. This command is very useful in checking the execution status of last command.

For example, I want to visit website tecmint.com using links command, in terminal but before that I need to check if the host is live or not.

4. OR Operator (||)

The OR Operator (||) is much like an ‘else‘ statement in programming. The above operator allow you to execute second command only if the execution of first command fails, i.e., the exit status of first command is ‘1‘.

For example, I want to execute ‘apt-get update‘ from non-root account and if the first command fails, then the second ‘links www.tecmint.com‘ command will execute.

In the above command, since the user was not allowed to update system, it means that the exit status of first command is ‘1’ and hence the last command ‘links tecmint.com‘ gets executed.

What if the first command is executed successfully, with an exit status ‘0‘? Obviously! Second command won’t execute.

Here, the user creates a folder ‘test‘ in his home directory, for which user is permitted. The command executed successfully giving an exit status ‘0‘ and hence the last part of the command is not executed.

5. NOT Operator (!)

The NOT Operator (!) is much like an ‘except‘ statement. This command will execute all except the condition provided. To understand this, create a directory ‘tecmint‘ in your home directory and ‘cd‘ to it.

Next, create several types of files in the folder ‘tecmint‘.

See we’ve created all the new files within the folder ‘tecmint‘.

Now delete all the files except ‘html‘ file all at once, in a smart way.

Just to verify, last execution. List all of the available files using ls command.

6. AND – OR operator (&& – ||)

The above operator is actually a combination of ‘AND‘ and ‘OR‘ Operator. It is much like an ‘if-else‘ statement.

For example, let’s do ping to tecmint.com, if success echo ‘Verified‘ else echo ‘Host Down‘.

Sample Output

Now, disconnect your internet connection, and try same command again.

Sample Output

7. PIPE Operator (|)

This PIPE operator is very useful where the output of first command acts as an input to the second command. For example, pipeline the output of ‘ls -l‘ to ‘less‘ and see the output of the command.

8. Command Combination Operator <>

Combine two or more commands, the second command depends upon the execution of the first command.

For example, check if a directory ‘bin‘ is available or not, and output corresponding output.

9. Precedence Operator ()

The Operator makes it possible to execute command in precedence order.

In the above pseudo command, what if the Command_x1 fails? Neither of the Command_x2, Command_x3, Command_x4 would executed, for this we use Precedence Operator, as:

Читайте также:  Как отформатировать весь жесткий диск windows 10

In the above pseudo command, if Command_x1 fails, Command_x2 also fails but Still Command_x3 and Command_x4 executes depends upon exit status of Command_x3.

10. Concatenation Operator (\)

The Concatenation Operator (\) as the name specifies, is used to concatenate large commands over several lines in the shell. For example, The below command will open text file test(1).txt.

That’s all for now. I am coming up with another interesting article very soon. Till then Stay tuned, healthy and connected to Tecmint. Don’t forget to give your Valuable feedback in our comment section.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Bash Operators in Linux

Although Linux Distributions provide a Graphical User Interface just like any other operating system, the ability to control the system via the command line interface (CLI) has many benefits. A way to control how tasks are executed or how input and output is redirected, can be done using operators.

1) Command “chaining”

Executing multiples tasks, one after another. After the first task is completed, the next task will execute. After the second is completed, the third will execute and so on:

  • Parallel execution: &

Execute tasks at the same time.

2) Conditional execution:

  • And operator: &&

Task 2 will be executed only if Task 1 was successful

  • Or operator: ||

Task 2 will be executed only if Task 1 was unsuccessful

  • Pipe operator: |

Used to send output from Task 1 (stdout) to input of Task 2 (stdin)

Error output of Task1 (stderr) is also redirected to input of Task 2 (stdin)

4) Input / output redirection

Used for commands that write output to the terminal.

command > file – write output to file. If file doesn’t exist, it is created. If it exists, it will be truncated

command >> file – write output to file. If file doesn’t exists, it is created. If it exists, output will be appended

Note: Stderr is still written to the terminal

Sends stderr to file.

command 2> file – write stderr to file. . If file doesn’t exist, it is created. If it exists, it will be truncated

command 2>> file – write stderr to file. If file doesn’t exist, it is created. If it exists, output will be appended

Note: Output (stdout) is still written to the terminal

  • Redirecting output – stdout and stderr: &>, &>>

Used to redirect both stdout and stderr for the same command

command &> file – send stdout and stderr to file. If file doesn’t exist, it is created. If it exists, it will be truncated

command &>> file – send stdout and stderr to file. If file doesn’t exist, it is created. If it exists, output will be appended

Interested in finding out more about Linux? Check out our trainings.

Источник

Оцените статью