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 :


file1 fil2



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

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

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

| improve this answer | |
  • 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 7:08

I use a function for this kind of thing:

echocmd() {
    echo "$@"


$ echocmd ls -ltr > ls_out.txt
| improve this answer | |
  • Thanks.. we can add this line too. echo "whoami@hostname""$" "$@" in place of echo "$@" – kumar Dec 19 '13 at 5:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.