aneesh ashok
aneesh ashok

Reputation: 11

Command redirection

How can I redirect output of a Linux commands along with the command to a file?

Like ls -l >> test.txt will only redirect the output and not the command also to the file. I am a novice

Upvotes: 1

Views: 81

Answers (2)

George Vasiliou
George Vasiliou

Reputation: 6345

If you don't want to use script utility there are some alternatives, using set -x bash feature:

$ exec 2>log; set -x; pwd >&2;set +x;exec 2>&1;cat log
+ pwd
/home/gv/Desktop/PythonTests
+ set +x

Or you can also use a custom function without tricky redirections:

$ function logme { a="$@"; echo $a >log ; "$@" >>log 2>&1;cat log;return; }
$ logme pwd  
pwd
/home/gv/Desktop/PythonTests

PS: You can offcourse send the output to another file , i.e logme pwd >>general log

Finally, you can build a custom script like bellow, making use also of set -v (verbose):

exec 3>&2 2>log 4<log 
set -vx
"$@" >&2
set +vx 
cat <&4 >&1  # Optionally combine with |tail -n +2 |head -n -2 
#The cat is used to display in command line what is logged inside the file.

Upvotes: 0

Akshay Hegde
Akshay Hegde

Reputation: 16997

Using script command you can log, which will save the entire terminal session until you exit the program, for example

Commands executed

akshay@db-3325:/tmp$ script test.log
Script started, file is test.log
akshay@db-3325:/tmp$ cal
     March 2017       
Su Mo Tu We Th Fr Sa  
          1  2  3  4  
 5  6  7  8  9 10 11  
12 13 14 15 16 17 18  
19 20 21 22 23 24 25  
26 27 28 29 30 31     

akshay@db-3325:/tmp$ uptime
 23:43:16 up  4:31,  1 user,  load average: 0.78, 0.67, 0.44
akshay@db-3325:/tmp$ w
 23:43:18 up  4:31,  1 user,  load average: 0.72, 0.66, 0.43
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
akshay   tty7     :0               19:12    4:31m  7:49   0.28s /sbin/upstart --user
akshay@db-3325:/tmp$ whoami
akshay
akshay@db-3325:/tmp$ echo 'something'
something
akshay@db-3325:/tmp$ exit
exit
Script done, file is test.log

This is what logged :

akshay@db-3325:/tmp$ cat test.log 
Script started on Thursday 16 March 2017 11:43:06 PM IST
akshay@db-3325:/tmp$ cal
     March 2017       
Su Mo Tu We Th Fr Sa  
          1  2  3  4  
 5  6  7  8  9 10 11  
12 13 14 15 16 17 18  
19 20 21 22 23 24 25  
26 27 28 29 30 31     

akshay@db-3325:/tmp$ uptime
 23:43:16 up  4:31,  1 user,  load average: 0.78, 0.67, 0.44
akshay@db-3325:/tmp$ w
 23:43:18 up  4:31,  1 user,  load average: 0.72, 0.66, 0.43
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
akshay   tty7     :0               19:12    4:31m  7:49   0.28s /sbin/upstart --user
akshay@db-3325:/tmp$ whoami
akshay
akshay@db-3325:/tmp$ echo 'something'
something
akshay@db-3325:/tmp$ exit
exit

Script done on Thursday 16 March 2017 11:43:38 PM IST

Upvotes: 1

Related Questions