RomanM
RomanM

Reputation: 6721

Bash Scripting - shell command output redirection

Can someone help explain the following:

If I type:

a=`ls -l`

Then the output of the ls command is saved in the variable a

but if I try:

a=`sh ./somefile`

The result is outputed to the shell (stdout) rather than the variable a

What I expected was the result operation of the shell trying to execute a scrip 'somefile' to be stored in the variable.

Please point out what is wrong with my understanding and a possible way to do this.

Thanks.

EDIT:

Just to clarify, the script 'somefile' may or may not exist. If it exsists then I want the output of the script to be stored in 'a'. If not, I want the error message "no such file or dir" stored in 'a'

Upvotes: 6

Views: 29567

Answers (3)

paxdiablo
paxdiablo

Reputation: 882426

I think because the shell probably attaches itself to /dev/tty but I may be wrong. Why wouldn't you just set execute permissions on the script and use:

a=`./somefile`

If you want to capture stderr and stdout to a, just use:

a=`./somefile 2>&1`

To check file is executable first:

if [[ -x ./somefile ]] ; then
    a=$(./somefile 2>&1)
else
    a="Couldn't find the darned thing."
fi

and you'll notice I'm switching to the $() method instead of backticks. I prefer $() since you can nest them (e.g., "a=$(expr 1 + $(expr 2 + 3))").

Upvotes: 15

phihag
phihag

Reputation: 288250

You are correct, the stdout of ./somefile is stored in the variable a. However, I assume somefile outputs to stderr. You can redirect that with 2>&1 directly after ./somefile.

Upvotes: 2

Bogdan
Bogdan

Reputation: 3075

You can try the new and improved way of doing command substitution, use $() instead of backticks.

a=$(sh ./somefile)

If it still doesn't work, check if somefile is not actually stderr'ing.

Upvotes: 5

Related Questions