Linux command output error

How to capture error message from executed command?

I was tasked to create an automated server hardening script and one thing that they need is a report of all the output of each command executed. I want to store the error message inside a string and append it in a text file. Let’s say I ran this command:

FATAL: Module hfsplus not found 

I tried running this command: var=$(/sbin/modprobe -n -v hfsplush) And then displaying it: $var But it still doesn’t capture the error message inside the string.

6 Answers 6

you can do it by redirecting errors command:

/sbin/modprobe -n -v hfsplus 2> fileName 
#!/bin/bash errormessage=$( /sbin/modprobe -n -v hfsplus 2>&1) echo $errormessage 
 #!/bin/bash errormessage=`/sbin/modprobe -n -v hfsplus 2>&1 ` echo $errormessage 

if you want to append the error use >> instead of >

Make sure to use 2>&1 and not 2> &1 to avoid the error «syntax error near unexpected token `&'»

I’ve tried that approach and it stores it DIRECTLY in the text file. I want it to store inside a string first so I can format the contents easily.

Someone reverted the edit I did, because I had a «syntax error near &» and removed the space after >. A justification would have been nice.

I tried to edit because : Make sure to use 2>&1 and not 2> &1 to avoid the error «syntax error near unexpected token `&'»

Simply to store as a string in bash script:

X=`/sbin/modprobe -n -v hfsplus 2>&1` echo $X 

This can be a bit better as you will see messages when command is executed:

TMP=$(mktemp) /sbin/modprobe -n -v hfsplus 2>&1 | tee $TMP OUTPUT=$(cat $TMP) echo $OUTPUT rm $TMP 

To return the error message in a variable, simply;

error=$(/sbin/modprobe -n -v hfsplus 2>&1 1>/dev/null) echo $error 

That’s the answer, since the other ones would append standard output to the variable. Usually, you want to know if the message comes from a error or not and that’s perfect. For example, to throw a warning or to handle a bad situation in a script.

Newer bash versions (I.e. bash 4.1+):

$ msg=$(ls -la nofile 2>&1) $ echo $msg ls: cannot access nofile: No such file or directory $ 

I capture error like this

if source failed, I will capture the error and log it.log_warn is just a simple function.

To append to a file use /sbin/modprobe -n -v hfsplus 2>> filename

You must log in to answer this question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.17.43537

Linux is a registered trademark of Linus Torvalds. UNIX is a registered trademark of The Open Group.
This site is not affiliated with Linus Torvalds or The Open Group in any way.

Читайте также:  Linux find exclude folder

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Working with Input Output and Error Redirection in Linux

Every process in Linux is provided with three open files( usually called file descriptor). These files are the standard input, output and error files. By default :

  • Standard Input is the keyboard, abstracted as a file to make it easier to write shell scripts.
  • Standard Output is the shell window or the terminal from which the script runs, abstracted as a file to again make writing scripts & program easier
  • Standard error is the same as standard output:the shell window or terminal from which the script runs.

A file descriptor is simply a number that refers to an open file. By default , file descriptor 0 (zero) refers to the standard input & often abbreviated as stdin. File descriptor 1 refers to standard output (stdout) and file descriptor 2 refers to standard error (stderr). These numbers are important when you need to access a particular file , especially when you want to redirect these files to the other locations, File descriptors numbers go up from zero.

Redirecting Standard Output

Syntax to redirect the output of a command to a file.

[email protected]:~$ cat /proc/cpuinfo > command.txt

We can see the data that would have gone to the screen with more command :

[email protected]:~$ more command.txt processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 37 model name : Intel(R) Core(TM) i3 CPU M 370 @ 2.40GHz stepping : 5 microcode : 0x616 cpu MHz : 0.000 cache size : 6144 KB physical id : 0 siblings : 2 core id : 0 cpu cores : 2 apicid : 0 initial apicid : 0 fpu : yes fpu_exception : yes cpuid level : 5 wp : yes

The > operator tells the shell to redirect the output of the command to the given file. If the file exists , the deletes the old contents of the file and replaces it with the output of the command.

Redirecting a Command’s Input

Syntax to redirect the input of a command to come from a file.

In this example , the input to the ‘wc‘ command comes from the file named command.txt. The shell sends the contents of the file command.txt as a standard input for the wc command.

Note : We can also combine both redirections with following syntax :

Redirecting Standard Error

In addition to redirecting the standard input and output for a script or a command, we can also redirect standard error. Even though standard error by defaults goes to the same place as the standard output – the shell window or terminal. There are good reasons why stdout and stderr are treated separately. The main reason is that we can redirect the output of a command or commands to a file but you have no way of knowing whether an error occurred. Separating stderr from stdout allows the error message to appear on your screen while output still goes to a file.

Syntax to redirect stderr from a command to a file.

# command_options_and_agruments 2> output_file.

The 2 in 2> refers to the file descriptor 2, the descriptor number for stderr.

[email protected]:~$ lsash /usr/bin 2> commands-error.txt [email protected]:~$ cat commands-error.txt No command 'lsash' found, did you mean: Command 'sash' from package 'sash' (universe) lsash: command not found

Redirecting both Standard Output & Standard Error

Use 2>&1 Syntax to redirect standard error to the same location as standard output .

Читайте также:  Установка дополнительной операционной системы linux ubuntu

Above Command has three parts.

  • ls /usr/bin is the command run
  • > command.txt redirects the output of the ls command
  • 2>&1 sends the output of the file descriptor 2, stderr , to the same location as the file descriptor 1, stdout.
[email protected]:~$ ls /usr2222/bin > command.txt 2>&1 [email protected]:~$ more command.txt ls: cannot access /usr2222/bin: No such file or directory

Note that above example assumes that your system doesn’t have directory names “/usr2222/bin”

Redirecting Both stderr & stdout at Once

[email protected]:~$ ls /usr2222/bin &> command.txt [email protected]:~$ more command.txt ls: cannot access /usr2222/bin: No such file or directory

In the above command ls is the command , /usr2222/bin is the argument to the ‘ls‘ command and ‘&> command.txt‘ redirect both stdout and stderr to a file named command.txt.

Appending To Files

Use the ‘>>’ operator to redirect the output of a command , but append to the file , if it exists. The syntax is given below :

[email protected]:~$ uptime >> sysload.txt [email protected]:~$ uptime >> sysload.txt [email protected]:~$ uptime >> sysload.txt [email protected]:~$ more sysload.txt 11:49:17 up 1:22, 3 users, load average: 0.28, 0.12, 0.11 11:49:28 up 1:22, 3 users, load average: 0.40, 0.15, 0.12 11:49:36 up 1:23, 3 users, load average: 0.33, 0.14, 0.12

Truncating Files :

We can use a shorthand syntax for truncating files by omitting the command before > operator . The Syntax is given below :

We can also use an alternate format with a colon :

Both of these command-less command will create the file if it does not exist and truncate the file to zero bytes if the file does exist.

[email protected]:~$ ls /usr/bin > command.txt [email protected]:~$ ls -l command.txt -rw-rw-r-- 1 linuxtechi linuxtechi 19713 Dec 2 12:18 command.txt [email protected]:~$ > command.txt [email protected]:~$ ls -l command.txt -rw-rw-r-- 1 linuxtechi linuxtechi 0 Dec 2 12:18 command.txt

Sending Output to Nowhere Fast

There are some scenarios where you not only want to redirect the output of a command , you want to throw the output away. You can do this by redirecting a command’s output to the null file “/dev/null” The null file consumes all output sent to it , as if /dev/null is a black hole star.

Note : The file /dev/null is often called a bit bucket.

Источник

Как перезагрузиться при «Input / Output Error»

Dec 1, 2016 17:31 · 167 words · 1 minute read hardware

Что делать, если при попытке запустить команду в консоли Linux выводится Input/Output Error ? Давайте разберемся!

В общем случае ситуация выглядит так:

du -bash: /usr/bin/du: Input/output error 
dmesg -bash: /bin/dmesg: Input/output error 
lsof -bash: /usr/bin/lsof: Input/output error 

Чаще всего проблема связана с неполадками системного диска (в конкретном случае используется SATA DOM). Первым делом нужно воспользоваться утилитой fsck , но увы:

fsck -bash: /sbin/fsck: Input/output error 

Либо диск совсем умер, либо проблема с физическим подключением накопителя (можно, например, попробовать заменить шлейф). В любом случае, пытаемся загрузиться с rescue disk и выполнить fsck или badblocks .

reboot -bash: /sbin/reboot: Input/output error 
shutdown -r now -bash: /sbin/shutdown: Input/output error 

Если есть физический доступ к серверу, то можно подойти и перезагрузить его с кнопки. В противном случае может помочь следующая комбинация:

echo 1 > /proc/sys/kernel/sysrq echo b > /proc/sysrq-trigger 

После загрузки с rescue disk’а и выполнения fsck все заработало, однако на production-серверах для системы лучше использовать RAID-массив. И даже в этом случае помнить: RAID is not backup!.

Read more

© Copyright 2023 Yevhen Lebid

Читайте также:  Nvidia quadro linux drivers

Источник

How to Redirect Output and Error to /dev/null in Linux

Learn how to redirect output or error or both to /dev/null in Linux so that it doesn’t show up on the screen.

Imagine this scenario. You run a Linux command and it has a huge output. You don’t want to see its output.

Or, you are using certain Linux commands in your script and you don’t want it to show any output or error on the terminal screen.

For such cases, you can take advantage of the output and error redirection and send them to /dev/null.

Send the output to /dev/null:

Send the error to /dev/null:

Send both output and error to /dev/null:

The /dev/null can be considered a black hole of the Linux file system so whatever you throw there can never see the light again.

Let’s take a detailed look here.

Redirect output to /dev/null in Linux

Let me start off with the basics. You type a command in the terminal is your input (let’s say I executed sudo apt update ).

So I gave input to my system and it will update the directories and it will show me the ongoing processes such as repositories being updated and packages that are outdated now:

In short, it gave the output showing what it did with the command. Now, here is the number designation for each standard data flow:

  • Standard input (stdin) is designated with 0
  • Standard output (stdout) is designated with 1
  • Standard error (stderr) is designated with 2

So now, let me show you how you can redirect standard output to the dev/null :

For example, I will intentionally use the find command which will show output with an error so as I redirect the output to /dev/null, the error should remain intact:

redirect output to dev null

As you can see, when I used the find command without redirecting the output, it showed output worth 1807 lines.

And when I redirected the output, it showed the errors only as it belongs to the standard error stream.

Redirect errors to /dev/null in Linux

As I mentioned earlier, the error stream is designated with 2. So you just have to make a few changes in the above command and you’d be good to go!

To redirect errors, you will have to use > symbol to redirect the data flow with the number 2 indicating it to redirect data flow on standard error.

For example, I will use sudo dnf update on Ubuntu so the error is obvious and on the second window, I will demonstrate how you can redirect the error:

redirect error to /dev/null in linux

Redirect both output and error to /dev/null in Linux

In this section, I will show you how you can redirect both output and the error to /dev/null.

The basic syntax for redirecting output and error to /dev/null is as follows:

command 1> /dev/null 2> /dev/null

Or you can also use the shorter version:

For this example, I will be using the find command to find files in the etc directory in which you’d need sudo privileges to access some sub-directors and when used without sudo, it will throw an error:

redirect output and error to /dev/null in linux

Wrapping Up

This was my take on how you can redirect the output and errors to /dev/null.

And if you want to learn more about redirecting data flow, I would highly recommend you the detailed guide on redirecting data flow in Linux.

Источник

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