Linux return code echo

How to get test command return code in the shell?

the above script have error in test command, because it seems parsing the output «ls — l» not return code. I know use the «if» syntax is work fine, But need more then one lines.

ls -l if [ $? -eq 0 ];then echo 'ok' fi 

It is quite unclear what you are asking. Mind to edit and specify what is the exact problem you are facing?

You misunderstand test command. There is no need to use it to simply check return code. One-liner equivalent for second piece of code is ls -l && echo ‘ok’ .

4 Answers 4

You can use && and || to make these things one-liner. For example, in the following:

echo ok will run only if the command before && ( ls -l ) returned 0 .

On the other hand, in the following:

echo ‘not ok’ will run only if the command before || returned non zero.

Also, you can make your if..else block one-liner using ; :

if ls -l;then echo ok;else echo 'not ok';fi 

But this may make your code hard to read, so not recommended.

The if statement is catching the return value of a command, for example with ls :

Another question here is how to wor below sample.

ls -l xxx || (echo "file xxx not exist" ; exit 1);echo "OK" 

As the sample. If file xxx does not exist. the 2nd echo OK still work even exit 1 previously.

I expect to exit return code 1 if file xxx does not exist.

[[ ]] is test and if the command returns successfully (return code of zero) then it executes the command after the && .

  • [[ ]] test
  • $( ) execute command
  • ls -l command to run
  • && run if test is successful

The command execution $(. ) makes this check for the output text, not for the return code. Check this for example: [[ $(echo abc && false) ]] && echo ok || echo no — it will print out «ok»

@viraptor, Thank you for the comments. The answer above checks for the return value and not the returned text of the command. You can see this by typing in [[ $(ls -l dirDoesNotExist ) ]] && echo «ok» || echo «not ok» and you will receive the «not ok» response. The command you included [[ $(echo abc && false) ]] successfully executes so it returns a return code of zero as expected. Let me know if you still disagree and we’ll continue to pursue it. Thanks!

I just want to add something here, in the short hand if statement using && and || does not equate directly to an if , else. If the command after && fails, the || clause will also run. Example: [[ true ]] && < echo "true"; false; >|| echo «false»

Читайте также:  Mount linux samba share to linux

Источник

Get the exit code for a command in Bash and KornShell (ksh)

Now if you look into this code, the few things that I changed are:

  • use of typeset is not necessary, but it is a good practice. It makes cmnd and ret_code local to safeRunCommand
  • use of ret_code is not necessary, but it is a good practice to store the return code in some variable (and store it ASAP), so that you can use it later like I did in printf «Error: [%d] when executing command: ‘$command'» $ret_code
  • pass the command with quotes surrounding the command like safeRunCommand «$command» . If you don’t then cmnd will get only the value ls and not ls -l . And it is even more important if your command contains pipes.
  • you can use typeset cmnd=»$*» instead of typeset cmnd=»$1″ if you want to keep the spaces. You can try with both depending upon how complex is your command argument.
  • ‘eval’ is used to evaluate so that a command containing pipes can work fine

Note: Do remember some commands give 1 as the return code even though there isn’t any error like grep . If grep found something it will return 0, else 1.

I had tested with KornShell and Bash. And it worked fine. Let me know if you face issues running this.

You can see the $command is being used in the safeRunCommand ‘s printf statement. You can use it as it is global. So I am going to change $command to $cmnd (the local variable..

Thanks @havexz. How can I run command like as: command=»ls -l | grep *.log» Unfortunately this command is not work, and all my commands are very complex with many pipe |, grep, awk, sed, .

One more question 🙂 How I can add output of the function safeRunCommand to variable, and in case of failure to process interrupts If I write output=$(safeRunCommand «$command») script is not being interrupt on error inside safeRunCommand function.

Maybe I found answer. Can I write out=$(eval $cmnd) , and after calling safeRunCommand function use out variable?

It should be $cmd instead of $($cmd) . It works fine with that on my box.

Your script works only for one-word commands, like ls. It will not work for «ls cpp». For this to work, replace cmd=»$1″; $cmd with «$@» . And, do not run your script as command=»some cmd»; safeRun command . Run it as safeRun some cmd .

Also, when you have to debug your Bash scripts, execute with ‘-x’ flag. [bash -x s.sh].

To quickly elaborate on why this is correct: $($cmd) will execute $cmd in a new shell, whereas $cmd won’t.

cmd=»$@» will not work; instead, either run «$@» directly (as in @sehe’s answer), or use an array: cmd=(«$@»); «$»

@GordonDavisson: I try on my system before posting anything here. And it is working fine. Here is output on bash -x try.sh . + command=’ls java’ + safeRunCommand ls java + cmnd=’ls java’ + ls java . It is same as doing cmd=»hello world», isn’t it?

Читайте также:  Linux check if port is open remote

@logic_max: try it on a command with a space in an argument, like safeRunCommand grep «this that» file.txt : + cmd=’grep this that file.txt’ + grep this that file.txt grep: that: No such file or directory

@logic_max: Yup. I’m not sure why people insist on storing commands in variables before executing them; it just created limitations like this.

There are several things wrong with your script.

Functions (subroutines) should be declared before attempting to call them. You probably want to return() but not exit() from your subroutine to allow the calling block to test the success or failure of a particular command. That aside, you don’t capture ‘ERROR_CODE’ so that is always zero (undefined).

It’s good practice to surround your variable references with curly braces, too. Your code might look like:

#!/bin/sh command="/bin/date -u" #. Example Only safeRunCommand() < cmnd="$@" #. insure whitespace passed and preserved $cmnd ERROR_CODE=$? #. so we have it for the command we want if [ $!= 0 ]; then printf "Error when executing command: '$'\n" exit $ #. consider 'return()' here fi > safeRunCommand $command command="cp" safeRunCommand $command 

cmnd=»$@» will not work; instead, either run «$@» directly (as in @sehe’s answer), or use an array: cmnd=(«$@»); «$»

The normal idea would be to run the command and then use $? to get the exit code. However, sometimes you have multiple cases in which you need to get the exit code. For example, you might need to hide its output, but still return the exit code, or print both the exit code and the output.

ec() < [[ "$1" == "-h" ]] && < shift && eval $* >/dev/null 2>&1; ec=$?; echo $ec; > || eval $*; ec=$?; > 

This will give you the option to suppress the output of the command you want the exit code for. When the output is suppressed for the command, the exit code will directly be returned by the function.

I personally like to put this function in my .bashrc file.

Below I demonstrate a few ways in which you can use this:

# In this example, the output for the command will be # normally displayed, and the exit code will be stored # in the variable $ec. $ ec echo test test $ echo $ec 0 
# In this example, the exit code is output # and the output of the command passed # to the `ec` function is suppressed. $ echo "Exit Code: $(ec -h echo test)" Exit Code: 0 
# In this example, the output of the command # passed to the `ec` function is suppressed # and the exit code is stored in `$ec` $ ec -h echo test $ echo $ec 0 

Solution to your code using this function

#!/bin/bash if [[ "$(ec -h 'ls -l | grep p')" != "0" ]]; then echo "Error when executing command: 'grep p' [$ec]" exit $ec; fi 

You should also note that the exit code you will be seeing will be for the grep command that’s being run, as it is the last command being executed. Not the ls .

Источник

Читайте также:  Bettercap установка kali linux

Making a Bash Script Return with Different Return Codes on Exit

Exit codes are integer numbers that indicate that a script has been successfully executed. These codes are also known as return codes or exit statuses. Exit codes usually return zero upon successful execution and non-zero upon unsuccessful execution.

However, many Bash script users want to return with different return codes on exit, but they get errors. In this tutorial, we will explain the different approaches to make a Bash script return with different return codes on exit.

Bash Script Returns with Different Return Codes on Exit

Before moving out to the methods, let’s take a look at the exit codes that have specific meanings:

Exit Codes Description
0 The script is executed successfully.
1 The script is executed with general errors.
2 Invalid use of some built-in commands in the script.
126 Shows the error for the command which is invoked and cannot be executed.
127 The command doesn’t exist in the script.
128 Shows the out-of-range exit code or fatal error signal.
130 CTRL+C terminates the script.
255 A general failure error code of the script.

How to Get Return Codes on Exit?

You only need to write the “echo $?” command to get the return code. For example, you want to compare two numbers using the following Bash script:

Once you execute the script in the terminal, run “echo $?” to get the return code on exit:

The “comparison.sh” is executed successfully. That’s why terminals show zero as the return code. Similarly, you will get non-zero as the successful execution of the script. For example, if you use the Ls instead of the ls command in the script, you may get the non-zero as the return code:

As you can see in the previous image, the terminal shows 127 as the return code because the script contained the wrong command:

Make a Bash Script Return with Different Exit Codes

You can manually set up the exit codes in the script. For example, if you want to get 255 as the exit code, use the following script:

Now, execute the script and then run the “echo $?” command to get 255 as the return code:

Conclusion

This is all about the exit codes that you may get after executing the Bash script in Linux. Exit codes help a user to identify the status of the Bash script. You can also manually set up and use the different return codes. Hence, you can get a non-zero exit code instead of zero even if the script is executed successfully. If you want to know more about the Bash scripts, browse our official website.

About the author

Prateek Jangid

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.

Источник

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