I have trawled the internet for this answer, but alas couldn’t find one.
In PHP I can run a command inside an if block, like so
if(command(blah)) {} else {}
As each function will return a truthy/falsey value. Can I do the same in a shell script? I want to echo output based on whether a command runs correctly. The commend to run is:
find . -type d -exec sudo chmod -R 775 {} \\;
I want to output that it ran successfully, or failed, then move on to another command.
Could I run the command into a variable or something similar?
Shell commands typically return an exit code indicating success or failure, with
0indicating success and anything else indicating some sort of error (the specifics will depend on what command you’re running).You can test for this exit code in an if statement:
And you can also chain commands together using the
||and&&operators.Your specific example with the
findcommand is a little tricky. Thechmodcommand might fail, but thefindcommand will still complete “successfully”. Something like this might help:This will print…
…for any place it fails, so you could check the output. But I’m not sure that’s absolutely necessary. There are few situations where your command is going to fail: e.g., on a read-only filesystem, or possibly on an NFS mount.