Skip to content

Commit b6cc6ba

Browse files
committed
Add Check If Command Is Executable Before Using as a unix til
1 parent 20d9a9b commit b6cc6ba

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-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-
_998 TILs and counting..._
13+
_999 TILs and counting..._
1414

1515
---
1616

@@ -911,6 +911,7 @@ _998 TILs and counting..._
911911
- [Change Default Shell For A User](unix/change-default-shell-for-a-user.md)
912912
- [Change To That New Directory](unix/change-to-that-new-directory.md)
913913
- [Check If A Port Is In Use](unix/check-if-a-port-is-in-use.md)
914+
- [Check If Command Is Executable Before Using](unix/check-if-command-is-executable-before-using.md)
914915
- [Check The Current Working Directory](unix/check-the-current-working-directory.md)
915916
- [Clear The Screen](unix/clear-the-screen.md)
916917
- [Command Line Length Limitations](unix/command-line-length-limitations.md)
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Check If Command Is Executable Before Using
2+
3+
When writing a quick bash script, you may want to check if a command exists and
4+
is executable before trying to call it. This can be done with `command`, a builtin shell command, and the `-v` flag.
5+
6+
> If the -V or -v option is supplied, the exit status is 0 if command was found, and 1 if not.
7+
8+
Knowing that, we can redirect the output of the command to `/dev/null` and then
9+
short-circuit executing the command if it's not available.
10+
11+
```bash
12+
command -v pbcopy >/dev/null 2>&1 && echo 'something' | pbcopy
13+
```
14+
15+
In this example, I execute the `pbcopy` command, which copies text to my system
16+
clipboard, only if that command is available and executable.
17+
18+
See `man bash` and find the listing for `command` for more details.

0 commit comments

Comments
 (0)