mirror of
https://github.com/jbranchaud/til
synced 2026-01-06 16:48:01 +00:00
Add Compare Two Variables In A Bash Script as a unix til
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
|||||||
|
|
||||||
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
|
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
|
||||||
|
|
||||||
_1017 TILs and counting..._
|
_1018 TILs and counting..._
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -932,6 +932,7 @@ _1017 TILs and counting..._
|
|||||||
- [Check The Current Working Directory](unix/check-the-current-working-directory.md)
|
- [Check The Current Working Directory](unix/check-the-current-working-directory.md)
|
||||||
- [Clear The Screen](unix/clear-the-screen.md)
|
- [Clear The Screen](unix/clear-the-screen.md)
|
||||||
- [Command Line Length Limitations](unix/command-line-length-limitations.md)
|
- [Command Line Length Limitations](unix/command-line-length-limitations.md)
|
||||||
|
- [Compare Two Variables In A Bash Script](unix/compare-two-variables-in-a-bash-script.md)
|
||||||
- [Configure cd To Behave Like pushd In Zsh](unix/configure-cd-to-behave-like-pushd-in-zsh.md)
|
- [Configure cd To Behave Like pushd In Zsh](unix/configure-cd-to-behave-like-pushd-in-zsh.md)
|
||||||
- [Copying File Contents To System Paste Buffer](unix/copying-file-contents-to-system-paste-buffer.md)
|
- [Copying File Contents To System Paste Buffer](unix/copying-file-contents-to-system-paste-buffer.md)
|
||||||
- [Copying Nested Directories With Ditto](unix/copying-nested-directories-with-ditto.md)
|
- [Copying Nested Directories With Ditto](unix/copying-nested-directories-with-ditto.md)
|
||||||
|
|||||||
26
unix/compare-two-variables-in-a-bash-script.md
Normal file
26
unix/compare-two-variables-in-a-bash-script.md
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
# Compare Two Variables In A Bash Script
|
||||||
|
|
||||||
|
You can compare two variables in a bash script with an `if` block like so:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
if [ "$EDITOR" = "$PREFERRED_EDITOR" ]; then
|
||||||
|
# do something ...
|
||||||
|
fi
|
||||||
|
```
|
||||||
|
|
||||||
|
If those variables are equal, then the contents of the `if` block will be
|
||||||
|
executed.
|
||||||
|
|
||||||
|
Notice that both variables are wrapped in quotes. This is to avoid a potential
|
||||||
|
syntax error. If the quotes were excluded and one of the variables happened to
|
||||||
|
be unset, then the comparison would evaluate to:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
if [ "vim" = ]; then
|
||||||
|
# do something ...
|
||||||
|
fi
|
||||||
|
```
|
||||||
|
|
||||||
|
That would cause an error, rather than evaluating to false and moving in.
|
||||||
|
Wrapping each in quotes allows an unset variable to turn into an empty string
|
||||||
|
(`""`).
|
||||||
Reference in New Issue
Block a user