user4330819
user4330819

Reputation: 11

how to use the if statement for error and warning messages in bash

I am writing my codes on gedit and I want to get the latest error and warning messages using if statement, if theres an error then I should get a warning messages.

cp /Volumes/Documents/criticalfile.txt /Volumes/BackUp/. 
if [ "?" != 0 ]; then 
    echo "[Error] copy failed!" 1>&2 
    exit 1 
fi

I've used the above code but I am not sure if its correct or not.

Upvotes: 0

Views: 400

Answers (3)

BMW
BMW

Reputation: 45243

fix your code.

cp /Volumes/Documents/criticalfile.txt /Volumes/BackUp/ > /dev/null 2>&1
if [ "$?" != 0 ]; then 
    echo "[Error] copy failed!"
    exit 1 
fi

one liner

cp infile /Volumes/BackUp/ > /dev/null 2>&1 || echo "[Error] copy failed!"

Upvotes: 0

janos
janos

Reputation: 124646

No, if [ "?" != 0 ] is not correct. You're looking for if [ $? != 0 ] instead.

But an even better way:

if ! cp /Volumes/Documents/criticalfile.txt /Volumes/BackUp/
then 
    echo "[Error] copy failed!" >&2 
    exit 1 
fi

I also dropped the 1 from 1>&2, as >&2 is the same thing.

Upvotes: 0

repzero
repzero

Reputation: 8412

You have to use

if [ "$?" != 0 ]; then

instead of

 if [ "?" != 0 ]; then 

Let say I want to copy a file but i don't know if I will get an error. I use the below command

cp -f /root/Desktop/my_new_file */root/t

definitely this will give me an error because copying to "*/root/t" is not possible.

I can check this by using the following codes

#!/bin/bash
cp -f /root/Desktop/my_new_file */root/t
if [ "$?" = 0 ];then
echo "No error"
else
echo "We have  error!"
fi

MY OUTPUT (Note the condition is working)

cp: cannot create regular file `*/root/t': No such file or directory
We have  error

Now let say I want to copy a file to a possible location like

cp -f /root/Desktop/my_new_file /root/t

I will get no error from cp command

OUTPUT

No error

Upvotes: 1

Related Questions