1

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
  • Still a bit curious, the fact that the error message you entered can not come from which, it should not give any message at all actually if, e.g., curl does not exist?
    – user986805
    Aug 7, 2021 at 17:28
  • Well, the output was "curl <and its version>" when it is found and it gave "curl not found" if not installed. But the latter output is seen in terminal only but not while using shell variables.
    – Sammy1410
    Aug 8, 2021 at 13:42
  • if curl is not installed, e.i., if the binary does not exist, it should not print any message at all. You can open which in a text editor, it's a very simple shell script, the message "curl not found" has to come from somewhere else. (and if curl exists, it should return the path, not curl <version>)
    – user986805
    Aug 8, 2021 at 13:50
  • Yes seems like it. This was just the small piece of code I was trying to put in if statement. Well, I found which command returns a boolean data that I could use. Thank you for helping. Finally, my code is running as expected.
    – Sammy1410
    Aug 8, 2021 at 14:18
  • And sorry my mistake which returned path not version. I mistook it with the other commands.
    – Sammy1410
    Aug 8, 2021 at 14:24

1 Answer 1

4

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
  • I tried but the result is still same.
    – Sammy1410
    Aug 8, 2021 at 13:38
  • As user bac0n suggested which did not give any output storable when the package was not found. I had to go the other way around for my main code to work.
    – Sammy1410
    Aug 8, 2021 at 14:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .