Bash Scripting - redirecting shell command output

Can someone help explain the following:

If I print:

a=`ls -l` 

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

but if I try:

 a=`sh ./somefile` 

The result is displayed in the shell ( stdout ), not the variable a

What I expected was the result of a shell trying to execute somefile 'script, which will be stored in a variable.

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

Thanks.

EDIT:

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

+6
scripting bash shell
source share
3 answers

I think because the shell probably joins / dev / tty, but I could be wrong. Why don't you just set the execution permissions for the script and use:

 a=`./somefile` 

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

 a=`./somefile 2>&1` 

First check the file do:

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

and you will notice that I am switching to the $ () method instead of backlinks. I prefer $ () since you can nest them (for example, " a=$(expr 1 + $(expr 2 + 3)) ".

+15
source share

You can try a new and improved way to perform command substitution, use $ () instead of $ backback.

 a=$(sh ./somefile) 

If it still does not work, check if any file is actually stderr'ing.

+5
source share

You are right, stdout ./somefile is stored in variable a . However, I assume some files are output to stderr. You can redirect this with 2>&1 immediately after ./somefile .

+2
source share

All Articles