Batch-file Echo

Windows 10, Windows 11, Windows 7, Windows 8, Windows Server, Windows Vista, Windows XP

  • 15.11.2016
  • 77 342

Batch-file 
 Echo

Командная строка – неизменный компонент любой операционной системы Windows, который берет свое происхождение прямиком от её предка – операционной системы MS-DOS. Данная программа имеет довольно широкие возможности, но сейчас мы поговорим о довольно примитивной вещи – сохранение (по факту – перенаправление) вывода командной строки в текстовый файл.

Почитать о том, как сделать тоже самое в LinuxBSD системах можно в этой статье.

Использование перенаправления выполнения команд

Batch-file 
 Echo

Обратите внимание, что командная строка при перенаправлении вывода может создать только текстовый файл, но не папку. Если вы введете несуществующий путь, то получите ошибку!

Как видно, командная строка не вывела никакого результата введенной команды на экран, но зато сохранила все в файл ping.txt. К сожалению, существуют ограничения перенаправления вывода, которые не позволяют одновременно отображать вывод и в окне командной строки, и сохранять их в текстовый файл. Однако, можно воспользоваться хитростью – сразу по завершению выполнения команды вывести содержимое текстового файла на экран с помощью команды type. Получится что-то следующее:

Batch-file 
 Echo

Содержимое получившегося текстового файла будет следующим:

Batch-file 
 Echo

Batch-file 
 Echo

  • Описание
  • Синтаксис
  • Параметры
  • Примеры использования
  • Справочная информация

Описание

Следующий пример представляет собой пакетный файл, выводящий сообщение из трех строк на экран с пустыми строками до и после него:

Справочная информация

Batch-file 
 Echo

Batch-file 
 Echo

Командная строка в Microsoft Windows по прежнему активно используется для осуществления различных действий с операционными системами Windows, в том числе и для упрощенного выполнения каких-либо задач, или автоматизации выполняемых действий. В данной статье мы рассмотрим, казалось бы, не сложную задачу – вывод сообщения средствами командой строки, и различные способы осуществления данной задачи.

Использование echo

Вот так будет выглядеть пример, выводящий сообщение “Привет мир!” в командной строке.

Batch-file 
 Echo

Дополнив пример выше несколькими дополнительными командами и пробелами, сделаем более “красивый” вариант с отображением текста в командной строке:

Batch-file 
 Echo

Использование msg

Программа msg поставляется вместе с Windows еще со времен версий Windows 2000 и Windows XP, и предназначена для передачи сообщений от одного пользователя другому пользователю. Она предлагает простые возможности по выводу сообщения, и так же проста в использовании.

В качестве примера, выведем сообщение “Привет мир!”:

Batch-file 
 Echo

Использование mshta

Mshta – программа, предназначенная для запуска приложений формата hta, которые представляют из себя программы, написанные с использованием HTML, CSS, JavaScript и VBScript. В данном случае, нам пригодиться возможность выполнения команд, написанных на языке JavaScript и VBScript. Используя знания данных языков, можно выводить сообщения.

Сперва рассмотрим возможности использования скриптового языка VBScript совместно с mshta.

mshta vbscript:Execute(“msgbox “”Привет мир!””:close”)

Batch-file 
 Echo

Добавим в наше сообщение заголовок “Пример”:

mshta vbscript:Execute(“msgbox “”Привет мир!””,0,””Пример””:close”)

Batch-file 
 Echo

Сделаем так, чтобы в сообщении были различные значки. Начнем со значка с ошибкой:

mshta vbscript:Execute(“msgbox “”Привет мир!””,16,””Заголовок””:close”)

Batch-file 
 Echo

Сменим его на вопросительный знак:

mshta vbscript:Execute(“msgbox “”Привет мир!””,32,””Заголовок””:close”)

Batch-file 
 Echo

Или, на значок информации:

mshta vbscript:Execute(“msgbox “”Привет мир!””,48,””Заголовок””:close”)

Batch-file 
 Echo

Теперь рассмотрим возможности mshta с JavaScript.

Отобразим сообщение “Привет мир!”:

mshta javascript:alert(“Привет мир!”);close();

Batch-file 
 Echo

Выведем сообщение, состоящее из нескольких строк:

mshta javascript:alert(“Привет мир!
И снова привет мир!

Все еще привет мир!”);close();

Batch-file 
 Echo

Использование PowerShell

Из командной строки так же можно вызвать оболочку PowerShell, передав ей все необходимые параметры, в результате чего будет отображено окно с нужным сообщением.

Batch-file 
 Echo

If we want to execute a series of commands/instructions we can do that by writing those commands line by line in a text file and giving it a special extension (e.g. .bat or .cmd for Windows/DOS and .sh for Linux) and then executing this file in the CLI application. Now all the commands will be executed (interpreted) serially in a sequence (one by one) by the shell just like any interpreted programming language. This type of scripting is called Batch Scripting (in Windows) and Bash Scripting (in Linux).

Example

Step 1: Open your preferred directory using the file explorer and click on View. Then go to the Show/hide section and make sure that the “File name extensions” are ticked.

Batch-file 
 Echo

Batch-file 
 Echo

Explanation

Batch-file 
 Echo

Printing a message on the screen using ECHO

Batch-file 
 Echo

Command Echoing

Batch-file 
 Echo

Let’s see the output.

Batch-file 
 Echo

Batch-file 
 Echo

Batch-file 
 Echo

Using <@echo off>

Batch-file 
 Echo

Batch-file 
 Echo

Printing the value of a variable

Note that we can put the %variable_name% anywhere between any text to be printed.

Batch-file 
 Echo

Concatenation of Strings

Batch-file 
 Echo

Batch-file 
 Echo

Display & Redirect Output

On this page I’ll try to explain how redirection works.
To illustrate my story there are some examples you can try for yourself.

For an overview of redirection and piping, view my original redirection page.

Display text

When I say “on screen”, I’m actually referring to the “DOS Prompt”, “console” or “command window”, or whatever other “alias” is used.

Streams

The output we see in this window may all look alike, but it can actually be the result of 3 different “streams” of text, 3 “processes” that each send their text to thee same window.

Those of you familiar with one of the Unix/Linux shells probably know what these streams are:

  • Standard Output
  • Standard Error
  • Console

Standard Error is the stream where many (but not all) commands send their error messages.

And some, not many, commands send their output to the screen bypassing Standard Output and Standard Error, they use the Console.
By definition Console isn’t a stream.

There is another stream, Standard Input: many commands accept input at their Standard Input instead of directly from the keyboard.
Probably the most familiar example is MORE:

(Since MORE’s Standard Input is used by DIR, MORE must catch its keyboard presses (the “Any Key”) directly from the keyboard buffer instead of from Standard Input.)

Redirection

You may be familiar with “redirection to NUL” to hide command output:

Now try this (note the typo):

‘EHCO’ is not recognized as an internal or external command, operable program or batch file.

This is a fine demonstration of only Standard Output being redirected to the NUL device, but Standard Error still being displayed.

A short demonstration. Try this command:

What you should get is:

Now make a typo again:

Now run test.bat in CMD.EXE and watch the result:

It looks like CMD.EXE uses 1 for Standard Output and 2 for Standard Error.
We’ll see how we can use this later.

:/>  Что за команда win l в чем состоит и как ее сочетать? Взакладки

Run test.bat in CMD.EXE, and this is what you’ll get:

Now let’s see if we can separate the streams again.
Run:

and you should see:

We redirected Standard Output to the NUL device, and what was left were Standard Error and Console.

We redirected Standard Error to the NUL device, and what was left were Standard Output and Console.

Nothing new so far. But the next one is new:

This time we redirected both Standard Output and Standard Error to the NUL device, and what was left was only Console.
It is said Console cannot be redirected, and I believe that’s true.
I can assure you I did try!

To get rid of screen output sent directly to the Console, either run the program in a separate window (using the START command), or clear the screen immediately afterwards (CLS).

Redirect “all” output to a single file

and you’ll get this text on screen (we’ll never get rid of this line on screen, as it is sent to the Console and cannot be redirected):

This text goes to the Console

This text goes to Standard Output
This text goes to Standard Error

Nothing is impossible, not even redirecting the Console output.

Unfortunately, it can be done only in the old MS-DOS versions that came with a CTTY command.

The general idea was this:

A pause or prompt for input before the CTTY CON command meant one had to press the reset button!

Besides being used for redirection to the NUL device, with CTTY COM1 the control could be passed on to a terminal on serial port COM1.

Escaping Redirection (not to be interpreted as “Avoiding Redirection”)

Redirection always uses the main or first command’s streams:

will redirect START’s Standard Output to logfile, not command’s!
The result will be an empty logfile.

A workaround that may look a bit intimidating is grouping the command line and escaping the redirection:

What this does is turn the part between parentheses into a “literal” (uninterpreted) string that is passed to the command interpreter of the newly started process, which then in turn does interpret it.
So the interpretation of the parenthesis and redirection is delayed, or deferred.

A safer way to redirect STARTed commands’ output would be to create and run a “wrapper” batch file that handles the redirection.
The batch file would look like this:

and the command line would be:

Some “best practices” when using redirection in batch files

  • Redirection overview page
  • Use the TEE command to display on screen and simultaneously redirect to file

Introduction

To display “Some Text”, use the command:

To display the strings On and Off (case insensitive) or the empty string, use a ( instead of white-space:

This will output:

<nul set/p=Some Text

Echo Setting

Quotes will be output as-is:

Comment tokens are ignored:

Echo output to file

Output to path

A little problem you might run into when doing this:

But what if you want to make a file that outputs a new file?

Then how do we do this?

Same goes for other stuff in batch

if we don’t want it to output “text” but just plain %example% then write:

to output the whole line we write:

If the variable is equal to “Hello” then it will say “True”, else it will say “False”

Turning echo on inside brackets

I’m using Windows 7 and I would like to quickly create a small text file with a few lines of text in the Command prompt.

I can create a single line text file with:

asked Nov 3, 2012 at 11:06

Batch-file 
 Echo

answered Nov 3, 2012 at 11:09

1 silver badge3 bronze badges

There are three ways.

All the above produce the same file:

answered Nov 3, 2012 at 11:26

1 gold badge21 silver badges22 bronze badges

If you REALLY want to type everything in a single line you can just put an & for each new line, like:

but efotinis’ answer is the easiest one.

answered Dec 4, 2021 at 16:31

You can put a space between each line to write:

answered Jan 21, 2019 at 14:02

WGET is a free tool to crawl websites and download files via the command line.

In this wget tutorial, we will learn how to install and how to use wget.

What is Wget?

Wget is free command-line tool created by the GNU Project that is used todownload files from the internet.

  • It lets you download files from the internet via FTP, HTTP or HTTPS (web pages, pdf, xml sitemaps, etc.).
  • It provides recursive downloads, which means that Wget downloads the requested document, then the documents linked from that document, and then the next, etc.
  • It lets you overwrite the links with the correct domain, helping you create mirrors of websites.

How to Install Wget

Open Terminal and type:

If it is installed, it will return the version.

Batch-file 
 Echo

Download Wget on Mac

The recommended method to install wget on Mac is with Homebrew.

https://youtube.com/watch?v=l2rF6qqKVzk%3Ffeature%3Doembed

First, install Homebrew.

Then, install wget.

Download Wget on Windows

To install and configure wget for Windows:

  • Download wget for Windows and install the package.
  • Copy the wget.exe file into your C:WindowsSystem32 folder.
  • Open the command prompt (cmd.exe) and run wget to see if it is installed.

https://youtube.com/watch?v=cvvcG1a7dOM%3Ffeature%3Doembed

Let’s look at the wget syntax, view the basic commands structure and understand the most important options.

View WGET commands

To view available wget commands, use wget -h.

Batch-file 
 Echo

14 Wget Commands to Extract Web Pages

Here are the 11 best things that you can do with Wget:

  • Download a single file
  • Download a files to a specific directory
  • Rename a downloaded files
  • Extract as Googlebot
  • Extract Robots.txt when it changes
  • Convert links on a page
  • Mirror a single page
  • Extract Multiple URLs from a list
  • Limit Speed
  • Number of attempts
  • Use Proxies
  • Continue Interrupted Downloads
  • Extract Entire Website
:/>  Восстановление системы через командную строку Windows 10: порядок действий

Download a single file with Wget

$ wget https://example.com/robots.txt

Download a File to a Specific Output Directory

To output the file with a different name:

Let’s extract robots.txt only if the latest version in the server is more recent than the local copy.

First time that you extract use -S to keep a timestamps of the file.

$ wget -S https://example.com/robots.txt

Later, to check if the robots.txt file has changed, and download it if it has.

$ wget -N https://example.com/robots.txt

Wget command to Convert Links on a Page

Convert the links in the HTML so they still work in your local version. (ex: example.com/path to localhost:8000/path)

$ wget –convert-links https://example.com/path

Mirror a Single Webpage in Wget

To mirror a single web page so that it can work on your local.

$ wget -E -H -k -K -p –convert-links https://example.com/path

Add all urls in a urls.txt file.

To be a good citizen of the web, it is important not to crawl too fast by using –wait and –limit-rate.

  • –wait=1: Wait 1 second between extractions.
  • –limit-rate=10K: Limit the download speed (bytes per second)

Define Number of Retry Attempts in Wget

$ wget -tries=10 https://example.com

How to Use Proxies With Wget?

To use proxies with Wget, we need to update the ~/.wgetrc file located at /etc/wgetrc.

You can modify the ~/.wgetrc in your favourite text editor

$ vi ~/.wgetrc # VI
$ code ~/.wgetrc # VSCode

And add these lines:

Then, by running any wget command, you’ll be using proxies.

Alternatively, you can use the -e command to run wget with proxies without changing the environment variables.

wget -e use_proxy=yes -e http_proxy=http://proxy.server.address:port/ https://example.com

How to remove the Wget proxies?

When you don’t want to use the proxies anymore, update the ~/.wgetrc to remove the lines that you added or simply use the command below to override them:

Continue Interrupted Downloads with Wget

When your retrieval process is interrupted, continue the download with restarting the whole extraction using the -c command.

$ wget -c https://example.com

This is extracting your entire site and can put extra load on your server. Be sure that you know what you do or that you involve the devs.

$ wget –recursive –page-requisites –adjust-extension –span-hosts –wait=1 –limit-rate=10K –convert-links –restrict-file-names=windows –no-clobber –domains example.com –no-parent example.com

$ wget –spider -r https://example.com -o wget.log

Wget VS Curl

Wget is strictly command line, but there is a package that you can import the wget package that mimics wget.

import wget
url = ‘http://www.jcchouinard.com/robots.txt’
filename = wget.download(url)
filename

Debug Wget Command Not Found

If you get the -bash: wget: command not found error on Mac, Linux or Windows, it means that the wget GNU is either not installed or does not work properly.

Go back and make sure that you installed wget properly.

Detail table about WGET

What is Wget Used For?

Wget is used to download files from the Internet without the use of a browser. It supports HTTP, HTTPS, and FTP protocols, as well as retrieval through HTTP proxies.

How Does Wget Work?

What is the Difference Between Wget and cURL?

Both Wget and cURL are command-line utilities that allow file transfer from the internet. Although, Curl generally offers more features than Wget, wget provide features such as recursive downloads.

Can you Use Wget With Python?

Yes, you can run wget get in Python by installing the wget library with $pip install wget

Does Wget Respect Robots.txt?

Yes, Wget respects the Robot Exclusion Standard (/robots.txt)

Is Wget Free?

Yes, GNU Wget is free software that everyone can use, redistribute and/or modify under the terms of the GNU General Public License

What is recursive download?

How to specify download location in Wget?

This is it.

You now know how to install and use Wget in your command-line.

Batch-file 
 Echo

SEO Strategist at Tripadvisor, ex- Seek (Melbourne, Australia). Specialized in technical SEO. In a quest to programmatic SEO for large organizations through the use of Python, R and machine learning.

I have Apache running on the Linux Server.

I have a file on the linux server that I want to download on my windows client.

I want to do it in 2 ways from the windows CMD:
-Using curl
-using wget

I tried the foll commands on my windows CMD. But doesnt work. Is something wrong with my CLI?

curl http://x.x.x.x/home/abc/ -O test.zip
wget http://x.x.x.x/home/abc/ -O test.zip

Edit:: Insense, I wanted to understand the right CLI syntax to do a wget/curl to fetch a file from a certain directory on the remote server (/home/abc)

asked Nov 16, 2021 at 23:13

If you want to retrieve a file stored on another server, you will prefer to use a tool like SCP which can get files throught SSH. Curl is commonly used for Web requests.

Graphicly, you can use WinSCP

answered Nov 17, 2021 at 13:12

1 silver badge11 bronze badges

No third party required, you can use PowerShell command Invoke-WebRequest.

Example:
Invoke-WebRequest http://x.x.x.x/home/abc/ -OutFile test.zip

There are additional arguments for adding headers, specifying authentication, and so forth.

answered Nov 22, 2021 at 20:23

How to download files from Command Prompt in Windows

Download and installation

Batch-file 
 Echo

Batch-file 
 Echo

  • Click “Install” then click “Finish” to proceed with the full installation.
  • After which, you will be prompted to save another file called “wget-1.11.4-1-src.zip”. Just click “Save” to confirm. Simply proceed to the next step as soon as you’re done.

Wget for Windows offers basic and advanced usage. However, in this post, we’re not going to delve into its advanced commands and functionalities. Since the objective of this post is just to let you know how to download files from the command prompt, you simply need to remember this basic Wget for Windows command:

Batch-file 
 Echo

  • Windows 95, 98, ME, NT, 2000, XP, 2003, Vista, 7, 2008 (Win32) with msvcrt.dll and msvcp60.dll
  • openssl

So that’s it. You’re done.

GNU Wget — консольная программа для загрузки файлов по сети. Поддерживает протоколы HTTP, FTP и HTTPS, а также работу через HTTP прокси-сервер. Программа включена почти во все дистрибутивы Linux. Утилита разрабатывалась для медленных соединений, поэтому она поддерживает докачку файлов при обрыве соединения.

:/>  Оснастки Windows. Команды вызова | Блог | РБ-Софт: Автоматизация бизнес-процессов

Для работы с Wget под Windows, переходим по ссылке и скачиваем файл wget.exe. Создаем директорию C:Program FilesWget-Win64 и размещаем в ней скачанный файл. Для удобства работы добавляем в переменную окружения PATH путь до исполняемого файла.

Если утилита ругается на сертификаты при скачивании по HTTPS, нужно использовать дополнительную опцию –no-check-certificate.

Загрузка всех URL, указанных в файле (каждая ссылка с новой строки):

wget -i download.txt

Скачивание файлов в указанный каталог:

wget -P /path/for/save ftp://ftp.example.org/image.iso

Скачивание файла file.zip и сохранение под именем archive.zip:

wget -O archive.zip http://example.com/file.zip

Продолжить загрузку ранее не полностью загруженного файла:

wget -c http://example.org/image.iso

Вывод заголовков HTTP серверов и ответов FTP серверов:

wget -S http://example.org/

wget -r –no-parent http://example.org/some/archive/

Использование имени пользователя и пароля на FTP/HTTP:

Отправить POST-запрос в формате application/x-www-form-urlencoded:

Сохранение cookie в файл cookie.txt для дальнейшей отправки серверу:

wget –save-cookie cookie.txt http://example.org/

Сохраненный файл cookie.txt:

# HTTP cookie file.
# Generated by Wget on 2018-09-14 11:40:37.
# Edit at your own risk.

example.org FALSE / FALSE 1570196437 visitor 71f61d2a01de1394f60120c691a52c56

Отправка cookie, сохраненных ранее в файле cookie.txt:

wget –load-cookie cookie.txt http://example.org/

Справка по утилите:

Дополнительно

Поиск:
CLI • Cookie • FTP • HTTP • HTTPS • Linux • POST • Web-разработка • Windows • wget • Форма

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Comments in batch files are usually placed in lines starting with REM (REMarks).

If you have many lines REMed out, this may slow down COMMAND.COM’s processing of the batch file.

As you probably know, COMMAND.COM reads a batch file, executes one command line, reads the batch file again, executes the next command line, etcetera.
This means each comment line causes one extra reread of the batch file; no problem when read from harddisk, but it may slow down batch file execution from slow floppy or network drives.

A workaround I have seen many times (back in the old days, when I was young, and dinosaurs roamed the Earth and harddisks were 20MB) is to convert the comment line to a label by starting the line with a colon ( : ).
COMMAND.COM skips labels it doesn’t have to jump to.

This method has the disadvantage that your batch file may “accidently” really use the label to jump to.

REM is a true command that may be used anywhere within a command line.
Though I doubt there is much use for a command like:

IF EXIST C:AUTOEXEC.BAT REM AUTOEXEC.BAT exists

it is valid and won’t generate an error message in any DOS or Windows version.

Labels, on the other hand, whether valid or not, should always start at the first non-whitespace character in a command line.

REM Comment line 1
REM Comment line 2
:Label1
:Label2
:: Comment line 3
:: Comment line 4
IF EXIST C:AUTOEXEC.BAT REM AUTOEXEC.BAT exists

are all allowed.
However,

IF EXIST C:AUTOEXEC.BAT :: AUTOEXEC.BAT exists

will result in a Syntax error message.

will result in an error message stating:

) was unexpected at this time.

will result in another error message:

Do something
The system cannot find the drive specified.

The same is true for FOR loops.
Try and see for yourself:

will also result in error messages.

Source: a discussion on comment styles on StackOverflow.com

A Mystery

Well, in Windows 7 they don’t!

The answer can be found at the end of this page.

More information on the subject:

  • Michael Klement’s summary of a discussion on comment styles on StackOverflow.com
    You will find even more comment styles here (like %= inline comments =%), each with its own list of pros and cons
  • Batch comments

(Thanks for Lee Wilbur and Michael Klement)

A possible pitfall, pointed out by Joost Kop, is a REM to comment out a line that uses redirection, as in:

In CMD.EXE (Windows NT 4 and later) the line is completely ignored (as was probably intended), but COMMAND.COM (MS-DOS, Windows 9x) interprets this line as “redirect the output of REM to logfile.log”, thus emptying the file logfile.log or creating a 0 bytes file logfile.log.

Summarizing

  • REM is the standards-compliant, documented statement to insert comments in batch files
  • double colons are a non-documented and non-compliant way to insert comments; there is no guarantee they will still work in future Windows versions
  • in theory, using double colons may speed up execution of batch files when run from a slow disk drive (e.g. floppy disk), but I doubt the difference can be detected on modern computers
  • since double colons are actually labels, they should be placed at the start of a command line; though leading whitespace is allowed, nothing else is
  • with COMMAND.COM be careful when using either REM or double colons to temporarily “disable” a command line, especially when it contains piping, redirection or variables
  • despite all, there is nothing wrong with using double colons for comments as long as you understand the limitations
  • test, test, test and test your batch files, including comment lines, on all Windows versions they will be used for

Pipe REM to block Standard Input

A really useful trick is to use REM combined with piping, as in:

The CHOICE command in itself would time out after 5 seconds (/T), except if someone presses a key not specified by /C, in which case the count down would be aborted.
By using REM and piping its (always empty) standard output to CHOICE’s standard input, this standard input will not receive keypresses from the console (keyboard) anymore.
So pressing a button neither speeds up CHOICE nor stops it.
(I borrowed this technique from “Outsider”, one of the alt.msdos.batch newsgroup’s “regulars”, and added the /C parameter to make it language independent)

Say “This line is true code”

Оставьте комментарий