"which" command output into a variable does not work

I am just a beginner at bash scripting. I tried to save output from the command "which" into a variable and printing it but the variable shows nothing. This is the code which I tried:

#!/bin/bash
OUTPUT="$(which curl)"
echo "${OUTPUT}"

Output:

user@user:~$ bash new.sh
user@user:~$

Also this works when I run it in terminal.

user@user:~$ OUTPUT="$(which curl)"
echo "${OUTPUT}"
curl not found
user@user:~$

But the thing is it works with other commands.

#!/bin/bash
OUTPUT="$(date)"
echo "${OUTPUT}"

Output:

user@user:~$ bash new.sh
Sat 07 Aug 2021 01:41:37 PM +0545
user@user:~$
5

1 Answer

The variable only accepts the value sent through STDOUT, or the output stream. Since curl cannot be found, the output you are seeing is an error message sent through STDERR or the error stream. If you wish to store the error message in the variable in the case of an error., do the following:

OUTPUT="$(which curl 2>&1)"

This directs all data from STDERR to STDOUT. 2 is the file descriptor for STDERR and 1 is the file descriptor for STDOUT.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like