0

I would like to redirect the command executed along with the output to a file.

for example: #ls >ls_out.txt

ls_out.txt should be something like :


ls

file1 fil2


Thanks!

kumar
  • 433
  • 3
  • 10
  • 23

2 Answers2

6

I use a function for this kind of thing:

echocmd() {
    echo "$@"
    "$@"
}

Then

$ echocmd ls -ltr > ls_out.txt
glenn jackman
  • 4,630
  • 1
  • 17
  • 20
  • Thanks.. we can add this line too. echo "`whoami`@`hostname`""$" "$@" in place of echo "$@" – kumar Dec 19 '13 at 05:37
2

You could use "script" command: Something like this:

localhost:test_sf user1$ ls
file1   file2   file3
localhost:test_sf user1$ script ls_out.txt  #starting script command ls_out.txt will contain output
Script started, output file is ls_out.txt
bash-3.2$ ls 
file1       file2       file3       ls_out.txt
bash-3.2$ exit
exit

Script done, output file is ls_out.txt
===================================================================================
localhost:test_sf user1$ cat ls_out.txt  #verify the contents now.
Script started on Wed Dec 18 12:05:23 2013
bash-3.2$ ls 
file1       file2       file3       ls_out.txt
bash-3.2$ exit
exit

You will just have to get rid off "bash-3.2$ exit exit" piece.

kumar
  • 433
  • 3
  • 10
  • 23
Danila Ladner
  • 5,331
  • 22
  • 31
  • Superb..I never know that there is something like "script" command exists in Linux . I kind of overlooked your answer and didn't understand it properly. – kumar Dec 20 '13 at 07:08