Linux скрыть вывод команды

Как скрыть вывод команды в Bash

Как я могу выполнить эту задачу? Я обязательно помогу сделать скрипт более удобным. В случае возникновения ошибки ее следует показать пользователю. Я хотел бы знать, как показать одно и то же сообщение при выполнении набора команд.

Возможный дубликат Как подавить весь вывод команды с помощью Баш? — person Ulrich Eckhardt &nbsp schedule 26.08.2019

Ответы (8)

Использовать этот.

Объяснение

your_command "Is anybody listening?" >&- 

Обычно вывод идет либо в файловый дескриптор 1 (stdout), либо в 2 (stderr). Если вы закроете файловый дескриптор, вам придется сделать это для каждого пронумерованного дескриптора, поскольку &> (ниже) — это специальный синтаксис BASH, несовместимый с >&- :

your_command "Hello?" > /dev/null 

Для перенаправления вывода в файл вы можете очень кратко направить как stdout, так и stderr в одно и то же место, но только в bash:

/your/first/command &> /dev/null 

Наконец, чтобы сделать то же самое для нескольких команд одновременно, заключите все в фигурные скобки. Bash рассматривает это как группу команд, объединяя дескрипторы выходного файла, чтобы вы может перенаправить все сразу. Если вы знакомы с подоболочками, использующими синтаксис ( command1; command2; ) , вы обнаружите, что фигурные скобки ведут себя почти так же, за исключением того, что, если вы не включите их в канал, фигурные скобки не будут создавать подоболочку и, таким образом, позволят вам устанавливать переменные внутри .

Дополнительные сведения, параметры и синтаксис см. В руководстве bash по перенаправлениям.

Привет, я знаю, что это старый вопрос, но можно ли сделать то же самое при определенных условиях? Как я хочу скрыть вывод при определенных условиях? Я знаю, что могу воспроизвести ту же часть в if-else, но есть ли лучший способ сделать это? — person usamazf; 06.04.2018

@UsamaZafar Я бы сделал это, установив переменную (параметр оболочки), который вы установили в /dev/null или /dev/stdout (или /path/to/a/logfile ) условно ранее в сценарии, а затем перенаправили в этот пункт назначения с помощью &> $output_dest (или как вы его называете). Если вы не хотите комбинировать stdout и stderr в этом случае, вы можете перенаправить их по отдельности, например > $output_dest 2> $errors_dest . — person Jeff Bowman; 06.04.2018

Читайте также:  Добавить репозитории линукс минт

Источник

Hiding output of a command

I have a script where it checks whether a package is installed or not and whether the port 8080 is being used by a particular process or not. I am not experienced at all with bash, so I did something like this:

if dpkg -s net-tools; then if netstat -tlpn | grep 8080 | grep java; then echo "Shut down server before executing this script" exit fi else echo "If the server is running please shut it down before continuing with the execution of this script" fi # the rest of the script. 

However when the script is executed I get both the dpkg -s net-tools and the netstat -tlpn | grep 8080 | grep java outputs in the terminal, and I don’t want that, how can I hide the output and just stick with the result of the if s? Also, is there a more elegant way to do what I’m doing? And is there a more elegant way to know what process is using the port 8080 (not just if it’s being used), if any?

3 Answers 3

To hide the output of any command usually the stdout and stderr are redirected to /dev/null .

Explanation:

1. command > /dev/null : redirects the output of command (stdout) to /dev/null
2. 2>&1 : redirects stderr to stdout , so errors (if any) also goes to /dev/null

&>/dev/null : redirects both stdout and stderr to /dev/null . one can use it as an alternate of /dev/null 2>&1

Silent grep : grep -q «string» match the string silently or quietly without anything to standard output. It also can be used to hide the output.

In your case, you can use it like,

if dpkg -s net-tools > /dev/null 2>&1; then if netstat -tlpn | grep 8080 | grep java > /dev/null 2>&1; then #rest thing else echo "your message" fi 

Here the if conditions will be checked as it was before but there will not be any output.

Reply to the comment:

Читайте также:  Linux флешка сохранение изменений

netstat -tlpn | grep 8080 | grep java > /dev/null 2>&1 : It is redirecting the output raised from grep java after the second pipe. But the message you are getting from netstat -tlpn . The solution is use second if as,

if [[ `netstat -tlpn | grep 8080 | grep java` ]] &>/dev/null; then 

Источник

How can I suppress all output from a command using Bash?

I have a Bash script that runs a program with parameters. That program outputs some status (doing this, doing that. ). There isn’t any option for this program to be quiet. How can I prevent the script from displaying anything? I am looking for something like Windows’ «echo off».

9 Answers 9

The following sends standard output to the null device (bit bucket).

And if you also want error messages to be sent there, use one of (the first may not work in all shells):

scriptname &>/dev/null scriptname >/dev/null 2>&1 scriptname >/dev/null 2>/dev/null 

And, if you want to record the messages, but not see them, replace /dev/null with an actual file, such as:

For completeness, under Windows cmd.exe (where «nul» is the equivalent of «/dev/null»), it is:

Note that ‘&>’ is peculiar to bash (and maybe C shells); Korn and Bourne shells require 2> /dev/null or 2>&1 (to send stderr to the same place as stdout). The Korn shell seems to interpret ‘&>’ as «run the stuff up to & in background, then do the i/o redirection on an empty command».

Note that some commands write directly to the terminal device rather than to standard output/error. To test, put echo foo > $(tty) in a script and run ./test.sh &> /dev/null — The output is still printed to the terminal. Of course this is not a problem if you’re writing a script which uses no such commands.

@l0b0, is there a way to make the script’s (or any other program’s) tty different so that all output is redirected regardless of your example? I know screen and script can do something like that but both are finicky and vary from *nix to *nix.

This will prevent standard output and error output, redirecting them both to /dev/null .

Читайте также:  Linux virbr0 what is

Even though I’m adding this to my gs (GhostScript) command, it still prints out **** Warning: File has a corrupted %%EOF marker, or garbage after %%EOF. Any advice?

An alternative that may fit in some situations is to assign the result of a command to a variable:

$ DUMMY=$( grep root /etc/passwd 2>&1 ) $ echo $? 0 $ DUMMY=$( grep r00t /etc/passwd 2>&1 ) $ echo $? 1 

Since Bash and other POSIX commandline interpreters does not consider variable assignments as a command, the present command’s return code is respected.

Note: assignement with the typeset or declare keyword is considered as a command, so the evaluated return code in case is the assignement itself and not the command executed in the sub-shell:

$ declare DUMMY=$( grep r00t /etc/passwd 2>&1 ) $ echo $? 0 

Источник

Как скрыть вывод команды в Bash

Я хочу сделать мои сценарии Bash более элегантными для конечного пользователя. Как скрыть вывод, когда Bash выполняет команды?

Например, когда Bash выполняет

Следующее будет отображаться пользователю, выполнившему Bash:

Loaded plugins: fastestmirror base | 3.7 kB 00:00 base/primary_db | 4.4 MB 00:03 extras | 3.4 kB 00:00 extras/primary_db | 18 kB 00:00 updates | 3.4 kB 00:00 updates/primary_db | 3.8 MB 00:02 Setting up Install Process Resolving Dependencies --> Running transaction check ---> Package nano.x86_64 0:2.0.9-7.el6 will be installed --> Finished Dependency Resolution Dependencies Resolved ================================================================================ Package Arch Version Repository Size ================================================================================ Installing: nano x86_64 2.0.9-7.el6 base 436 k Transaction Summary ================================================================================ Install 1 Package(s) Total download size: 436 k Installed size: 1.5 M Downloading Packages: nano-2.0.9-7.el6.x86_64.rpm | 436 kB 00:00 warning: rpmts_HdrFromFdno: Header V3 RSA/SHA256 Signature, key ID c105b9de: NOKEY Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6 Importing GPG key 0xC105B9DE: Userid : CentOS-6 Key (CentOS 6 Official Signing Key) Package: centos-release-6-4.el6.centos.10.x86_64 (@anaconda-CentOS-201303020151.x86_64/6.4) From : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6 Running rpm_check_debug Running Transaction Test Transaction Test Succeeded Running Transaction Installing : nano-2.0.9-7.el6.x86_64 1/1 Verifying : nano-2.0.9-7.el6.x86_64 1/1 Installed: nano.x86_64 0:2.0.9-7.el6 Complete!

Теперь я хочу скрыть это от пользователя и вместо этого показать:

Как я могу выполнить эту задачу? Я обязательно помогу сделать скрипт более удобным. В случае возникновения ошибки ее следует показать пользователю.

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

Источник

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