Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

like image 901
RomanM Avatar asked Feb 06 '09 07:02

RomanM


People also ask

How do I redirect a bash output?

The append >> operator adds the output to the existing content instead of overwriting it. This allows you to redirect the output from multiple commands to a single file. For example, I could redirect the output of date by using the > operator and then redirect hostname and uname -r to the specifications.

How do I redirect an output shell?

Append Redirect shell commandThe >> shell command is used to redirect the standard output of the command on the left and append (add) it to the end of the file on the right.

How do you redirect output?

When the notation >filename is added to the end of a command, the output of the command is written to the specified file name. The > symbol is known as the output redirection operator. The output of a process can be redirected to a file by typing the command followed by the output redirection operator and file name.

How do I redirect echo output to a file in shell script?

$ echo “Hello” > hello. txt The > command redirects the standard output to a file. Here, “Hello” is entered as the standard input, and is then redirected to the file **… $ cat deserts.


1 Answers

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))").

like image 168
paxdiablo Avatar answered Oct 20 '22 22:10

paxdiablo