From b6cc6ba298cb42dd01972c9ffe40520467da17e5 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 7 Jan 2021 14:33:34 -0600 Subject: [PATCH] Add Check If Command Is Executable Before Using as a unix til --- README.md | 3 ++- ...ck-if-command-is-executable-before-using.md | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 unix/check-if-command-is-executable-before-using.md diff --git a/README.md b/README.md index 1cc2293..3efdee4 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/unix/check-if-command-is-executable-before-using.md b/unix/check-if-command-is-executable-before-using.md new file mode 100644 index 0000000..3a34729 --- /dev/null +++ b/unix/check-if-command-is-executable-before-using.md @@ -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.