Skip to content

Commit 667bfbd

Browse files
committed
Add Compare Two Variables In A Bash Script as a unix til
1 parent 190d178 commit 667bfbd

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1017 TILs and counting..._
13+
_1018 TILs and counting..._
1414

1515
---
1616

@@ -932,6 +932,7 @@ _1017 TILs and counting..._
932932
- [Check The Current Working Directory](unix/check-the-current-working-directory.md)
933933
- [Clear The Screen](unix/clear-the-screen.md)
934934
- [Command Line Length Limitations](unix/command-line-length-limitations.md)
935+
- [Compare Two Variables In A Bash Script](unix/compare-two-variables-in-a-bash-script.md)
935936
- [Configure cd To Behave Like pushd In Zsh](unix/configure-cd-to-behave-like-pushd-in-zsh.md)
936937
- [Copying File Contents To System Paste Buffer](unix/copying-file-contents-to-system-paste-buffer.md)
937938
- [Copying Nested Directories With Ditto](unix/copying-nested-directories-with-ditto.md)
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Compare Two Variables In A Bash Script
2+
3+
You can compare two variables in a bash script with an `if` block like so:
4+
5+
```bash
6+
if [ "$EDITOR" = "$PREFERRED_EDITOR" ]; then
7+
# do something ...
8+
fi
9+
```
10+
11+
If those variables are equal, then the contents of the `if` block will be
12+
executed.
13+
14+
Notice that both variables are wrapped in quotes. This is to avoid a potential
15+
syntax error. If the quotes were excluded and one of the variables happened to
16+
be unset, then the comparison would evaluate to:
17+
18+
```bash
19+
if [ "vim" = ]; then
20+
# do something ...
21+
fi
22+
```
23+
24+
That would cause an error, rather than evaluating to false and moving in.
25+
Wrapping each in quotes allows an unset variable to turn into an empty string
26+
(`""`).

0 commit comments

Comments
 (0)