LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Checking the result from a command executed. (https://www.linuxquestions.org/questions/linux-newbie-8/checking-the-result-from-a-command-executed-929284/)

Jakkie 02-14-2012 08:16 AM

Checking the result from a command executed.
 
Hi,

How can I test the result of a command? In DOS, one can use errorlevel to check the return code and based in this, take further steps. I want to move a file from one directory to another with:

Code:

mv /usr/test/myfile /usr/test/archive/myfile
Then, before I move on to the next step, make sure that the file was indeed moved. If it was not moved, I want to raise some alert. If it was moved, then simply carry on with the rest of the code.

How can I do this?

Thanks,
J

acid_kewpie 02-14-2012 08:35 AM

You've marked this as solved... can you provide any feedback incase others find it useful?

Jakkie 02-14-2012 08:46 AM

I may have been a bit quick on the draw on this one, but I though I had is solved. What I did was:

Code:

if [ -f filename ]
then
echo "file was moved"
else
echo "warning"
fi

The problem is, after I moved it, the filename is obviously no longer the same. It consists out of the the new path and filename that was moved. For instance, moving /usr/test/myfile to /usr/test/archive/myfile, the latter is the new full path. What I need is the filename only to do the search...

J

acid_kewpie 02-14-2012 08:58 AM

I didn't actually read your question, just that it was solved with no reply...


the equivalent to that awful ERRORLEVEL nonsense is the $? shell variable:


Code:

# ls -l 1234
-rw-r--r-- 1 root webusers 0 Feb 14 14:56 1234
# echo $?
0
# ls -l 5678
ls: 5678: No such file or directory
# echo $?
2

and if you want to get the filename from a path, use the basename command:

Code:

# basename /usr/bin/ls
ls


Jakkie 02-14-2012 09:01 AM

Aha, are you saying that invoking the echo $? immediately after a command will give me the return code of that command?

acid_kewpie 02-14-2012 09:10 AM

yup

Jakkie 02-14-2012 09:16 AM

That's exactly what I was looking for! Thanks bud, its working.


All times are GMT -5. The time now is 05:51 AM.