Сохранить файл linux terminal

How do I save terminal output to a file?

How do I save the output of a command to a file? Is there a way without using any software? I would like to know how.

10 Answers 10

Yes it is possible, just redirect the output (AKA stdout ) to a file:

Or if you want to append data:

If you want stderr as well use this:

if you want to have both stderr and output displayed on the console and in a file use this:

SomeCommand 2>&1 | tee SomeFile.txt 

(If you want the output only, drop the 2 above)

Note that someCommand 2> someFile.txt and someCommand 2>> someFile.txt also redirects stterr to someFile.txt

I’m trying to do this with gcc command but it doesn’t work. It works with other commands, but not this one. It simply creates the output file with nothing inside it.

@Nik-Lz Often this is because the command is sending all its output on stderr. If gcc is generating error messages, this seems likely. See Slothworks comment for how to capture stderr instead of stdout.

NB: to get the output of the make command into a file it requires this syntax instead: make > someFile.txt 2>&1 (source: linuxquestions.org/questions/linux-newbie-8/…)

To write the output of a command to a file, there are basically 10 commonly used ways.

Overview:

Please note that the n.e. in the syntax column means «not existing».
There is a way, but it’s too complicated to fit into the column. You can find a helpful link in the List section about it.

 || visible in terminal || visible in file || existing Syntax || StdOut | StdErr || StdOut | StdErr || file ==========++==========+==========++==========+==========++=========== > || no | yes || yes | no || overwrite >> || no | yes || yes | no || append || | || | || 2> || yes | no || no | yes || overwrite 2>> || yes | no || no | yes || append || | || | || &> || no | no || yes | yes || overwrite &>> || no | no || yes | yes || append || | || | || | tee || yes | yes || yes | no || overwrite | tee -a || yes | yes || yes | no || append || | || | || n.e. (*) || yes | yes || no | yes || overwrite n.e. (*) || yes | yes || no | yes || append || | || | || |& tee || yes | yes || yes | yes || overwrite |& tee -a || yes | yes || yes | yes || append 

List:

  • command > output.txt The standard output stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, it gets overwritten.
  • command >> output.txt The standard output stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, the new data will get appended to the end of the file.
  • command 2> output.txt The standard error stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, it gets overwritten.
  • command 2>> output.txt The standard error stream will be redirected to the file only, it will not be visible in the terminal. If the file already exists, the new data will get appended to the end of the file.
  • command &> output.txt Both the standard output and standard error stream will be redirected to the file only, nothing will be visible in the terminal. If the file already exists, it gets overwritten.
  • command &>> output.txt Both the standard output and standard error stream will be redirected to the file only, nothing will be visible in the terminal. If the file already exists, the new data will get appended to the end of the file..
  • command | tee output.txt The standard output stream will be copied to the file, it will still be visible in the terminal. If the file already exists, it gets overwritten.
  • command | tee -a output.txt The standard output stream will be copied to the file, it will still be visible in the terminal. If the file already exists, the new data will get appended to the end of the file.
  • (*) Bash has no shorthand syntax that allows piping only StdErr to a second command, which would be needed here in combination with tee again to complete the table. If you really need something like that, please look at «How to pipe stderr, and not stdout?» on Stack Overflow for some ways how this can be done e.g. by swapping streams or using process substitution.
  • command |& tee output.txt Both the standard output and standard error streams will be copied to the file while still being visible in the terminal. If the file already exists, it gets overwritten.
  • command |& tee -a output.txt Both the standard output and standard error streams will be copied to the file while still being visible in the terminal. If the file already exists, the new data will get appended to the end of the file.
Читайте также:  Astra linux драйвер radeon

Источник

Как сохранить и выйти из nano в терминале

Nano — это редактор на основе командной строки, известный своей простотой по сравнению с другими редакторами, такими как Vim и Emacs. Но если вы новичок в Nano, выполнение основных операций, таких как создание файлов, сохранение файла и выход из редактора, может вызвать у вас недоумение. Поэтому в этой статье я хочу показать вам, как сохранить ваш код в Nano и выйти из него.

Как сохранить файл в Nano

Шаг 1: Откройте терминал, введите «nano» и нажмите ENTER, чтобы попасть в редактор кода Nano

Запуск редактора nano

Шаг 2: Напишите свой код или текст на любом языке. На скриншоте ниже я написал немного PHP.

Текст в редакторе nano

Если у вас не работает подсветка синтаксиса, включите ее, нажав ALT + 4. Если подсветка синтаксиса все еще не появилась, сохраните файл.

Шаг 3: Нажмите CTRL + O, чтобы сохранить файл, введите имя файла и нажмите ENTER.

Сохранение файла в nano

Теперь подсветка синтаксиса включена:

Подсветка синтаксиса в nano

Если вы уже открыли файл, набрав

Когда вы закончите вносить изменения, нажмите CTRL + O и нажмите ENTER, чтобы сохранить изменения.

Как выйти из Nano

Чтобы выйти из nano, достаточно нажать CTRL + X.

Как выйти из Nano

Если у вас есть изменения, которые не были сохранены, вам будет предложено сохранить изменения перед выходом из редактора.

Подведение итогов

Надеюсь, эта статья помогла вам узнать, как сохранить файл в Nano и выйти из редактора, когда захотите.

  • Набрав nano, вы попадаете в редактор Nano в терминале.
  • CTRL + O сохраняет файл в Nano
  • CTRL + X выход из Nano

Похожие записи:

Источник

Save all the terminal output to a file

Many GUI terminal emulators allow to save the scroll buffer, but this is not accessible to commands (leaving aside xdotool and this sort of black art).

Читайте также:  Linux посмотреть данные пользователя

4 Answers 4

You can use script . It will basically save everything printed on the terminal in that script session.

script makes a typescript of everything printed on your terminal. It is useful for students who need a hardcopy record of an interactive session as proof of an assignment, as the typescript file can be printed out later with lpr(1). 

You can start a script session by just typing script in the terminal, all the subsequent commands and their outputs will all be saved in a file named typescript in the current directory. You can save the result to a different file too by just starting script like:

To logout of the script session (stop saving the contents), just type exit .

$ script output.txt Script started, file is output.txt $ ls output.txt testfile.txt foo.txt $ exit exit Script done, file is output.txt 
$ cat output.txt Script started on Mon 20 Apr 2015 08:00:14 AM BDT $ ls output.txt testfile.txt foo.txt $ exit exit Script done on Mon 20 Apr 2015 08:00:21 AM BDT 

script also has many options e.g. running quietly -q ( —quiet ) without showing/saving program messages, it can also run a specific command -c ( —command ) rather than a session, it also has many other options. Check man script to get more ideas.

Can it be invoked after the fact? (i.e. At the end of a session) Or does it have to be invoked before the content you want logged?

To export it retroactively, try Terminal menu -> Shell -> Export text as, like here: mactricksandtips.com/2013/04/save-terminals-text-output.html

@Magne you should note in your comment that it is specific to the terminal utility in Mac. gnome-terminal, for one, does not have that menu, so we should assume that other linux terminal windows won’t have it either.

Читайте также:  Узнать процессор линукс консоль

I too faced the same problem and after some search came up with this solution:

Add to your .bash_aliases this:

# Execute "script" command just once smart_script() < # if there's no SCRIPT_LOG_FILE exported yet if [ -z "$SCRIPT_LOG_FILE" ]; then # make folder paths logdirparent=~/Terminal_typescripts logdirraw=raw/$(date +%F) logdir=$logdirparent/$logdirraw logfile=$logdir/$(date +%F_%T).$$.rawlog # if no folder exist - make one if [ ! -d $logdir ]; then mkdir -p $logdir fi export SCRIPT_LOG_FILE=$logfile export SCRIPT_LOG_PARENT_FOLDER=$logdirparent # quiet output if no args are passed if [ ! -z "$1" ]; then script -f $logfile else script -f -q $logfile fi exit fi ># Start logging into new file alias startnewlog='unset SCRIPT_LOG_FILE && smart_script -v' # Manually saves current log file: $ savelog logname savelog() < # make folder path manualdir=$SCRIPT_LOG_PARENT_FOLDER/manual # if no folder exists - make one if [ ! -d $manualdir ]; then mkdir -p $manualdir fi # make log name logname=$logname=$ # add user logname if passed as argument if [ ! -z $1 ]; then logname=$logname'_'$1 fi # make filepaths txtfile=$manualdir/$logname'.txt' rawfile=$manualdir/$logname'.rawlog' # make .rawlog readable and save it to .txt file cat $SCRIPT_LOG_FILE | perl -pe 's/\e([^\[\]]|\[.*?[a-zA-Z]|\].*?\a)//g' | col -b > $txtfile # copy corresponding .rawfile cp $SCRIPT_LOG_FILE $rawfile printf 'Saved logs:\n '$txtfile'\n '$rawfile'\n' > 

And to the end of your .bashrc file add this:

After you’ve done this, «script» command will be executed once in every terminal session, logging everything to ~/Terminal_typescripts/raw .

If you want, you can save current session log after the fact (in the end of the session) by typing savelog or savelog logname – this will copy current raw log to ~/Terminal_typescripts/manual and also create readable .txt log in this folder. (If you forget to do so, raw log files will still be in their folder; you’ll just have to find them.) Also you may start recording to a new log file by typing startnewlog .

There will be a lot of junk log files, but you can clean old ones from time to time, so it’s not a big problem.

Источник

Оцените статью
Adblock
detector