mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 15:18:01 +00:00
Add Check If Command Is Executable Before Using 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).
|
||||
|
||||
_998 TILs and counting..._
|
||||
_999 TILs and counting..._
|
||||
|
||||
---
|
||||
|
||||
@@ -911,6 +911,7 @@ _998 TILs and counting..._
|
||||
- [Change Default Shell For A User](unix/change-default-shell-for-a-user.md)
|
||||
- [Change To That New Directory](unix/change-to-that-new-directory.md)
|
||||
- [Check If A Port Is In Use](unix/check-if-a-port-is-in-use.md)
|
||||
- [Check If Command Is Executable Before Using](unix/check-if-command-is-executable-before-using.md)
|
||||
- [Check The Current Working Directory](unix/check-the-current-working-directory.md)
|
||||
- [Clear The Screen](unix/clear-the-screen.md)
|
||||
- [Command Line Length Limitations](unix/command-line-length-limitations.md)
|
||||
|
||||
18
unix/check-if-command-is-executable-before-using.md
Normal file
18
unix/check-if-command-is-executable-before-using.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# Check If Command Is Executable Before Using
|
||||
|
||||
When writing a quick bash script, you may want to check if a command exists and
|
||||
is executable before trying to call it. This can be done with `command`, a builtin shell command, and the `-v` flag.
|
||||
|
||||
> If the -V or -v option is supplied, the exit status is 0 if command was found, and 1 if not.
|
||||
|
||||
Knowing that, we can redirect the output of the command to `/dev/null` and then
|
||||
short-circuit executing the command if it's not available.
|
||||
|
||||
```bash
|
||||
command -v pbcopy >/dev/null 2>&1 && echo 'something' | pbcopy
|
||||
```
|
||||
|
||||
In this example, I execute the `pbcopy` command, which copies text to my system
|
||||
clipboard, only if that command is available and executable.
|
||||
|
||||
See `man bash` and find the listing for `command` for more details.
|
||||
Reference in New Issue
Block a user