Linux and or operators

Difference between [[ ]] AND [ ] or (( )) AND ( ) in Bash

[[. ]] does everything that [. ] does. The difference is that word splitting and glob expansion are not performed for variables inside [[. ]] so quoting the variables is not so crucial. Additionally, [[ can do pattern matching with the == operator and regular expression matching with the =~ operator.

The reason [[ 10 > 9 ]] gives you an unexpected result is that the > operator inside [[. ]] is for string comparison and the string «10» is «less than» the string «9».

Yes. But look at the documentation (such as help if at a bash prompt) — ANY command can be used as the condition of an if statement. The branching is based on the exit status of the command. [[ and (( produce an exit status

About ((…)) and (…)

As stated in this other answer, ((…)) is the shell’s arithmetic construct (a bashism) and (…) runs command(s) in a subshell. They are very different from each other and from [ … ] or [[ … ]] .

On the other hand [ … ] and [[ … ]] are very similar in simple cases; they may be confused. The rest of this answer concentrates on [ … ] and [[ … ]] .

Formal note

  • to elaborate on differences and similarities between [ … ] and [[ … ]] ;
  • to provide a canonical answer in the subject of [ … ] vs [[ … ]] , so questions that can be answered by » [ is not [[ » can be linked here;
  • to provide an answer exhaustive enough, so users are no longer tempted to post answers that focus on a single difference each.

What is [ ?

  1. [ performs a test. The purpose of [ is to test something (e.g. if some file exists) and to return exit status zero if the test succeeds, non-zero otherwise.
  2. [ is a command. [ is a command name like cat or echo . [ (like echo ) is a builtin in Bash, but this only means it can be run without spawning an additional process, it still behaves like a command. There is probably a standalone [ executable in your system (e.g. /bin/[ ); try type -a [ in Bash to find out.
  3. [ requires a space after. As a command, [ takes arguments. Like with any other command, arguments must be separated one from another and from the command name. [foo is a different command name, it is not equivalent to [ foo (similarly and more obviously echoHello world is not echo Hello world ). You certainly need a space (or a tab) after [ .
  4. [ requires ] . [ requires ] as the last argument, otherwise it refuses to work. This is only to make [ … ] stand out as a block, as if it was some special syntax; but it’s not a special syntax. To pass ] as the last argument you need a space (or a tab) before it. For comparison: the last argument in [ … bar] is bar] which is not ] , so [ … bar] is not a valid command.
  5. [ is (almost) like test . [ … ] is equivalent to test … . In other words you can convert any [ command to a test command by removing the ] and changing the command name. And you can convert any test command to a [ command by changing the command name and adding ] .
  6. [ is not special. It’s good to remember [ is not special, it’s only a somewhat fancy name for a command. If you acknowledge this then you won’t be surprised by the fact that all the parsing and processing the shell does before running a command ( test or echo , ls etc.) also happens if the command is [ . In particular:
    • [ is not aware if you quoted any of its arguments, it gets arguments after the shell removes quotes.
    • Unquoted and unescaped && or || between [ and ] is not interpreted as an argument to [ . In other words [ … || … ] is interpreted as [ … (invalid because there is no ] ) and … ] (a separate command, whatever … is) logically connected with || , exactly like command1 || command2 .
  7. [ is specified by POSIX. There is the POSIX specification for [ / test . You can call [ portable. Notes:
    • Some primaries are extensions, some are marked as obsolescent. E.g. our invalid code ( [ … || … ] ) can be fixed as [ … -o … ] , but since -o is obsolescent, a better fix is [ … ] || [ … ] .
    • Implementations may support more primaries. The [ builtin in Bash does (see help test ); the [ binary (like /bin/[ ) in your OS may (see man test ).
Читайте также:  Утилита для ssd linux

What is [[ ? How is [[ different than [ ?

Notes:
— The question is tagged bash, now we’re talking about [[ in Bash.
— The numbered paragraphs in this section correspond to the numbered paragraphs in the previous section.

  1. (similarity) [[ performs a test. The purpose of [[ is to test something (e.g. if some file exists) and to return exit status zero if the test succeeds, non-zero otherwise. [[ can test anything [ can, and more.​
  2. (difference) [[ is a keyword. ​ [[ is a shell keyword (invoke type [[ in Bash to confirm this). Like the [ builtin, the [[ keyword belongs to Bash; but it does not behave like a command.
  3. (similarity) [[ requires a space after. (Or a tab).
  4. (similarity) [[ requires ]] . [[ requires ]] later in the code, however it’s not only to make [[ … ]] stand out as a block. It is a special syntax (a difference, we will get to it). You need a space (or a tab) before ]] .
  5. (difference) There is no ordinarily-looking command equivalent to [[ . There is no other command/keyword/whatever that can replace [[ in the way test can replace [ .
  6. (difference) [[ is special. [[ changes the way the shell parses and interprets the code, up to the matching ]] . Normal parsing and processing the shell does before running [ or test (or echo , ls etc.) does not apply inside [[ … ]] . In particular:
    • [[ is aware if you quoted any of its «arguments». Double-quoting variables is not necessary (while normally it is), but in some cases double-quoting a string (or a variable) makes a difference (see this answer where it mentions «the right-hand side of = or == or != or =~ «).
    • && or || between [[ and ]] belongs to the [[ … ]] construct. [[ … || … ]] can be a valid piece of code, virtually equivalent to [[ … ]] || [[ … ]] .
  7. (difference) [[ is not specified by POSIX. ​ [[ is not portable. [[ works in Bash, it doesn’t work in pure sh . Other shells may support [[ (e.g. Zsh does) but their [[ may be different than the [[ of Bash. [[ is not designed to comply with the specification of [ / test . In many cases replacing [ with [[ and ] with ]] will give you a [[ … ]] snippet equivalent to the original [ … ] snippet; but not always, sometimes the inside needs to be adjusted. So don’t change [ to [[ blindly. Blindly changing [[ to [ is even more risky because there are tests [[ can do while [ cannot.
Читайте также:  Операционная система linux краткая характеристика

Other notes:

  1. Neither [ nor [[ is a part of the if … then … syntax. Remember if just tests the exit status of some code. if true; then … is valid, if sleep 5; then … is valid, similarly if [ … ]; then … or if [[ … ]]; then … is valid (if the [ … ] or [[ … ]] part is itself a valid snippet). Since ((…)) or (…) also returns some exit status (that depends on what’s inside), it may be used after if as well.
  2. Personally I prefer using [ for any test [ can easily do, resorting to [[ when really necessary. This way I don’t get used to non-portable [[ and I know what I can do in a shell not as rich as Bash.
  3. The [ executable in your OS may not be strictly equivalent to the [ builtin in your Bash. If [ is invoked by Bash then the builtin will do the job. If [ is invoked by something else, then the executable will do the job. E.g. find … -exec [ … ] … uses the executable. There is no standard [[ executable (at least in the systems I know), so find … -exec [[ … ]] … will never work. If there was a [[ executable then it would have to behave like a command, it wouldn’t be able to mimic the keyword.

Источник

How to Use Logical OR & AND in Shell Script with Examples

Logical operators are used to combine multiple conditions in a script, allowing for more complex decision-making. The two most commonly used logical operators in shell scripting are Logical OR (||) and Logical AND (&&).

These operators are used in conditional statements like if, while, and until, as well as in command chaining. Command chaining is a technique where multiple commands are executed in a sequence, based on the success or failure of previous commands.

  • The Logical OR operator (||) is used to execute the command following it only if the previous command fails (returns a non-zero exit status).
  • The Logical AND operator (&&) is used to execute the command following it only if the previous command is successful (returns a zero exit status).
Читайте также:  Radeon hd 7570 linux

1. Using Logical OR (||) in Shell Scripts

Logical OR in bash script is used with operator -o. Write a small shell script that will show how to use logical OR ( || ) operator between two conditions.

This shell script prompts the user to input two numeric values. It then checks if either the first value is less than or equal to 10, or the second value is greater than 20. If at least one of these conditions is met, the script outputs “At least one condition is true.” Otherwise, it outputs “Both conditions are failed.”

2. Using Logical AND (&&) in Shell Scripts

Logical AND in bash script is used with operator -a. Below shell script will show you to how to use logical AND ( && ) between two conditions.

This shell script prompts the user to input two numeric values. It then checks if the first value is less than or equal to 10 and the second value is greater than 20. If both conditions are met, the script outputs “Both conditions are true.” Otherwise, it outputs “At least one condition is false.”

3. Using Multiple Logical OR & AND

Now, use the multiple logical operators in a single statement. The below example will help you to understand how to use multiple logical operators in a single statement.

This shell script allows a user to input a number and then checks if the entered number lies within either the range of 10-20 or 100-200. The script then outputs a message to the user indicating whether the input number falls within one of these specified ranges or not.

4. A Practical Example

In this practical example, we’ll create a shell script that checks if a server is reachable and if a specific directory exists on the local machine. If both conditions are met, the script will create a backup of the directory and transfer it to the remote server using scp. If any of these conditions are not met, it will print an appropriate error message.

Create a file called backup_and_transfer.sh and add the following content:

This script demonstrates the use of Logical AND (&&) and Logical OR (||) operators to chain commands, create backup files, and transfer them to a remote server, while handling errors and providing useful feedback.

Conclusion

Mastering the Logical OR (||) and Logical AND (&&) operators in shell scripting enables you to create efficient and effective scripts for managing systems and automating tasks. By understanding their usage and combining them as needed, you can create complex decision trees and streamline your shell scripts. Remember to follow best practices, such as using parentheses to group conditions and leveraging short-circuit evaluation, to optimize your scripts and ensure they work as intended. With practice and a thorough understanding of these logical operators, you’ll be well on your way to becoming a shell scripting expert.

Источник

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