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
'
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.
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.
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.
$ 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.
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))
").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With