LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Bash : add cr to stdout (https://www.linuxquestions.org/questions/linux-general-1/bash-add-cr-to-stdout-580972/)

romainp 08-30-2007 10:08 AM

Bash : add cr to stdout
 
Hi,
Maybe it is a simple question for you guys but I a newby in bash script programming...
Here it is :

When in a script I do a
Code:

z=$(ls -al 2>&1)
echo $z
var=$?

the output for z give the good result but with no new line or carriage return.

Is there a simple way to output the result of the command and display it with carriage return for each new line?
By the way, I want to retrieve stdrr so that's why I am using 2>&1 and var=$?.

Thanks

theYinYeti 08-30-2007 10:20 AM

Two things:
- The answer is: surround your $(...) construct with double quotes.
- The return status stored in var is that of the echo command. You probably want to have the var= line just under the ls -al line; however, I'm not sure you'll get the return status of ls -al as this command is burried in a subshell...

Yves.

romainp 08-30-2007 10:39 AM

Quote:

Originally Posted by theYinYeti (Post 2875792)
Two things:
- The answer is: surround your $(...) construct with double quotes.
- The return status stored in var is that of the echo command. You probably want to have the var= line just under the ls -al line; however, I'm not sure you'll get the return status of ls -al as this command is burried in a subshell...

Yves.

Thanks for replying me!
Well I have tested your solution but that's not seems to work...
Ok, here is the code
Code:

        z="$(ls -al 2>&1)"
        var=$?
        echo $z

The output is :
Code:

total 12 drwxr-x--- 2 romain romain 4096 Aug 30 11:22 . drwx------ 10 romain romain 4096 Aug 30 11:22 .. -rwxr-x--- 1 romain romain 1303 Aug 30 11:22 test.sh
What I want is :
Code:

total 12
drwxr-x---  2 romain romain 4096 Aug 30 11:22 .
drwx------  10 romain romain 4096 Aug 30 11:22 ..
-rwxr-x---  1 romain romain 1303 Aug 30 11:22 test.sh

As you can see, the output of ls does not add any carriage return or new line code..

I will check for the stderr stuff later.

Thanks

theYinYeti 08-30-2007 10:58 AM

Yes I forgot that you ALSO have to put double quotes around the variable name as an argument to echo, which gives:
Code:

z="$(ls -al 2>&1)"
var=$?
echo "$z"

Yves.

romainp 08-30-2007 11:05 AM

SOLVED : Bash : add cr to stdout
 
Perfect! That's working.
By the way, I have tested the stderr code and it seems to catch successfully the error code (0 or 1) when the ls function is executed.


All times are GMT -5. The time now is 11:04 AM.