"Too many arguments" error in shell script - bash

Here's my script:
if [ awk '$0 ~ /Failed/ { print }' $(pwd)/unity.log ]; then
echo "Build Failed"
exit 1
else
echo "Build Success"
exit 0
fi
The gist is that I am checking the file for "Build Failed" message and exiting 1 if failed.
If what I understand is correct, awk will return blank string if there is no text in the file and some text if it's found. But it shoots syntax error : ./Scripts/build.sh: line 41: [: too many arguments

Remove the [], use grep:
if grep -qw Failed unity.log; then
echo "Build Failed"
exit 1
else
echo "Build Success"
exit 0
fi

You could take advantage of the default exit value being 0. Also, there's no reason to do $(pwd)/filename; just do filename.
grep -qw Failed unity.log || { echo "Build Failed"; exit 1; }
echo "Build Success"
It would be also more idiomatic to send the error message on failure to stderr (with echo >&2).

try this:
if [ ! "$(grep 'Build Failed' unity.log)" ]; then
exit 1
fi

Related

Ignore exit code in bash

I'm testing about exit codes in bash and I coded the following script:
read -p "Path: " path
dr $path 2> /dev/null
echo "Command output level: "$?
if [ $? = 0 ]
then
echo "Command success"
elif [ $? = 127 ]
then
echo "Command not found"
else
echo "Command failed or not found"
fi
Now, I've been doing some research and I want to know if there's a way to make the very last "echo" avoid changing the exit code, if there's any I haven't found it.
I understand that the exit code is changed from 127 (yes, dr is on purpose to provoke the exit code) to 0 when I executed it.
Every command sets $?. If you wish to preserve the exit status of a specific command, you must save the value immediately.
dr $path 2> /dev/null
dr_status=$?
echo "Command output level: $dr_status"
if [ $dr_status = 0 ]
then
echo "Command success"
elif [ $dr_status = 127 ]
then
echo "Command not found"
else
echo "Command failed or not found"
fi
However, you can sometimes avoid repeated commands that would reset $?. For example,
dr $path 2> /dev/null
case $? in
0) echo "Command success" ;;
127) echo "Command not found" ;;
*) echo "Command failed or not found" ;;
esac

Bash equality not behaving as I expect it

I want to check if last command failed or not in bash. I base this mini script on this
#!/bin/bash
mkdir nothere/cantcreate
echo $?
if [ $? -eq 0 ]; then
echo "command succeed"
else
echo "command failed"
fi
This prints the following:
mkdir: cannot create directory ‘nothere/cantcreate’: No such file or
directory
1
command succeed
I expect it to print command failed as the value of $? is 1. Why does the equality not behave as I expect ?
As mentioned in comment section, when you get to the if-clause $? evaluates to the exit code of echo $?.
The most straightforward and fool-proof way is to put the command itself in the if-clause:
#!/bin/bash
if mkdir nothere/cantcreate; then
echo "command succeed"
else
echo "command failed"
fi
echo $? itself is command that succeeds printing exit code of failed mkdir. If you want to capture exit code of mkdir you need to store it right after command call.
#!/bin/bash
mkdir nothere/cantcreate
RESULT=$?
echo $RESULT
if [ $RESULT -eq 0 ]; then
echo "command succeed"
else
echo "command failed"
fi

Only run code if git tag exists for current commit in BASH [duplicate]

What would be the best way to check the exit status in an if statement in order to echo a specific output?
I'm thinking of it being:
if [ $? -eq 1 ]
then
echo "blah blah blah"
fi
The issue I am also having is that the exit statement is before the if statement simply because it has to have that exit code. Also, I know I'm doing something wrong since the exit would obviously exit the program.
Every command that runs has an exit status.
That check is looking at the exit status of the command that finished most recently before that line runs.
If you want your script to exit when that test returns true (the previous command failed) then you put exit 1 (or whatever) inside that if block after the echo.
That being said, if you are running the command and are wanting to test its output, using the following is often more straightforward.
if some_command; then
echo command returned true
else
echo command returned some error
fi
Or to turn that around use ! for negation
if ! some_command; then
echo command returned some error
else
echo command returned true
fi
Note though that neither of those cares what the error code is. If you know you only care about a specific error code then you need to check $? manually.
Note that exit codes != 0 are used to report errors. So, it's better to do:
retVal=$?
if [ $retVal -ne 0 ]; then
echo "Error"
fi
exit $retVal
instead of
# will fail for error codes == 1
retVal=$?
if [ $retVal -eq 1 ]; then
echo "Error"
fi
exit $retVal
An alternative to an explicit if statement
Minimally:
test $? -eq 0 || echo "something bad happened"
Complete:
EXITCODE=$?
test $EXITCODE -eq 0 && echo "something good happened" || echo "something bad happened";
exit $EXITCODE
$? is a parameter like any other. You can save its value to use before ultimately calling exit.
exit_status=$?
if [ $exit_status -eq 1 ]; then
echo "blah blah blah"
fi
exit $exit_status
For the record, if the script is run with set -e (or #!/bin/bash -e) and you therefore cannot check $? directly (since the script would terminate on any return code other than zero), but want to handle a specific code, #gboffis comment is great:
/some/command || error_code=$?
if [ "${error_code}" -eq 2 ]; then
...
Just to add to the helpful and detailed answer:
If you have to check the exit code explicitly, it is better to use the arithmetic operator, (( ... )), this way:
run_some_command
(($? != 0)) && { printf '%s\n' "Command exited with non-zero"; exit 1; }
Or, use a case statement:
run_some_command; ec=$? # grab the exit code into a variable so that it can
# be reused later, without the fear of being overwritten
case $ec in
0) ;;
1) printf '%s\n' "Command exited with non-zero"; exit 1;;
*) do_something_else;;
esac
Related answer about error handling in Bash:
Raise error in a Bash script
If you are writing a function – which is always preferred – you can propagate the error like this:
function()
{
if <command>; then
echo worked
else
return
fi
}
Now, the caller can do things like function && next as expected! This is useful if you have a lot of things to do in the if block, etc. (otherwise there are one-liners for this). It can easily be tested using the false command.
Using Z shell (zsh) you can simply use:
if [[ $(false)? -eq 1 ]]; then echo "yes" ;fi
When using Bash and set -e is on, you can use:
false || exit_code=$?
if [[ ${exit_code} -ne 0 ]]; then echo ${exit_code}; fi
This might only be useful in a limited set of use-cases, I use this specifically when I need to capture the output from a command and write it to a log file if the exit code reports that something went wrong.
RESULT=$(my_command_that_might_fail)
if (exit $?)
then
echo "everything went fine."
else
echo "ERROR: $RESULT" >> my_logfile.txt
fi
you can just add this if statement:
if [ $? -ne 0 ];
then
echo 'The previous command was not executed successfully';
fi
Below test scripts below work for
simple bash test commands
multiple test commands
bash test commands with pipe included:
if [[ $(echo -en "abc\n def" |grep -e "^abc") && ! $(echo -en "abc\n def" |grep -e "^def") ]] ; then
echo "pipe true"
else
echo "pipe false"
fi
if [[ $(echo -en "abc\n def" |grep -e "^abc") && $(echo -en "abc\n def" |grep -e "^def") ]] ; then
echo "pipe true"
else
echo "pipe false"
fi
The output is:
pipe true
pipe false

Setting exit codes in Unix shell scripts

I have test.sh which has multiple return condition and test1.sh just echo statement.When i run test2.sh my logic should run test.sh process the file i.e "File successfully" and call test1.sh script .It should not run the test1.sh script when other else condition was executed.i.e "File not successfully", "Input file doesn't exists in directory"
The problem i am facing is when it is executing other condition like "File not successfully", "Input file doesn't exists in directory" it is not retuning "1" as specified exit code but in turn returning 0 i.e from the OS means job was successful. So i am getting "0" from test.sh for all the different condition so test1 .sh is getting called irrespective if the file processed failed etc.Pls advice with the return code
test.sh
FILES=/export/home/input.txt
cat $FILES | nawk -F '|' '{print $1 "|" $2 "|" }' $f > output.unl
if [[ -f $FILES ]];
then if [[ $? -eq 0 ]]; then
echo "File successfully"
else
echo "File not successfully"
exit 1
fi
else
echo "Input file doesn't exists in directory" exit 1 fi
========================================================================
test1.sh
echo "Input file exists in directory"
test2.sh
echo "In test2 script"
./test.sh
echo "return code" $?
if [[ $? -eq 0 ]]; then
echo "inside"
./test1.sh
fi
You're overwriting $? when you use it in echo - after that, it contains the exit code of echo itself. Store it in a variable to avoid this.
echo "In test2 script"
./test.sh
testresult=$?
echo "return code" $testresult
if [[ $testresult -eq 0 ]]; then
echo "inside"
./test1.sh
fi
Edited to add: it's hard to tell what you want from test.sh as the code you pasted is incomplete and doesn't even run. It looks like you meant the cat to be inside the if, because otherwise it errors when the input file is missing, and your $? test does nothing. So I rearranged it like this:
FILES=input.txt
if [[ -f $FILES ]]; then
cat $FILES | awk -F '|' '/bad/{ exit 1 }'
if [[ $? -eq 0 ]]; then
echo "File processed successfully"
else
echo "File processing failed"
exit 1
fi
else
echo "Input file doesn't exist in directory"
exit 1
fi
I've changed the awk script to demonstrate the conditions all work: now, if I put the word bad in input.txt you'll see the "File processing failed" message, otherwise you see success; remove the file and you'll see the input file doesn't exist message.

From bash to ksh - script throws errors but still works

I have created a simple BASH script that checks every hour for the presence of a file on a remote server. It worked error-free until I was asked to move it to a server that runs KSH.
The portion of code that errors-out is this one:
connect_string=$UID#$SERVER:$srcdir/$EVENTFILE
result=`sftp -b "$connect_string" 2>&1`
if [ echo "$result" | grep "not found" ]; then
echo "not found"
else
echo "found"
fi
These are the errors it throws:
-ksh: .[51]: [: ']' missing
grep: ]: No such file or directory
found
It still runs though and confirms that the file I am polling for is there but I need to fix this. I changed the if statement like so
if [[ echo "$result" | grep "not found" ]]; then
but it fails right away with this error
-ksh: .: syntax error: `"$result"' unexpected
What am I missing?
Your basic syntax assumptions for if are incorrect. The old [...] syntax, calls the test builtin, and [[...]] is for textual pattern matching.
As #shelter's comment, the correct syntax is:
connect_string="$UID#$SERVER:$srcdir/$EVENTFILE"
result=`sftp -b "$connect_string" 2>&1`
if echo "$result" | grep "not found" ; then
echo "not found"
else
echo "found"
fi
But this is an unnecessary use of the external grep program, you can use shell text comparison:
if [[ $result == *not\ found* ]] ; then
echo "not found"
else
echo "found"
fi
(tested with bash and ksh)
Your solution:
EXIT=`echo $?`
if [ $EXIT != 0 ]
then
...
fi
Can be improved. First, if you are going to do an arithmetic comparison, then use ((...)), not test, and I can't figure out why you have the EXIT variable:
if (( $? != 0 ))
then
...
fi
But to go full circle, you actually only need:
if sftp -b "$connect_string" 2>&1
then
...
fi
echo "$result" | grep "not found"
#capture exit status code from previous command ie grep.
if [[ $? == 0 ]]
than
echo "not found"
else
echo "found"
fi
It appears you're struggling with a basic tenet of bash/ksh control structures.
Between the if and the then keywords, the shell expects one or more commands, with
the last command in the series deciding how the if statement is processed.
The square brackets are only needed if you actually need to perform a comparison. Internally they are equivalent to the test command - if the comparison succeeds, it
results in an exit status of 0.
Example:
$ [ a == a ]
$ echo $?
0
$ [ a == b ]
$ echo $?
1
Which is equivalent to:
$ test a == a
$ echo $?
0
$ test a == b
$ echo $?
1
I changed my approach to this.
connect_string=$UID#$SERVER:$srcdir/$EVENTFILE
result=`sftp "$connect_string" 2>&1`
EXIT=`echo $?`
if [ $EXIT != 0 ]
then
echo "file not found"
exit 1
else
echo "file found"
exit 0
fi
It takes care of my problem. Thanks to all.

Resources