Hacker News new | past | comments | ask | show | jobs | submit login

Nooo! Mistake #0 about shell scripting is thinking [ is syntax. It makes it way more weird and inexplicable. [ is a command, just like any other. That's why there needs to be a space between it and the next thing, and why you have to use weird looking flags and such. This is why I prefer the command `test`. It does the same thing as `[`, but is more obviously a command. And when you see it as a command, it's obvious that any command can be used in an if directly; if is just checking the exit code. (Whenever I see someone doing `if [ $? -ne 0 ]`, it makes me cry.)



I'll bite. What should we be using instead of `if [ $? -ne 0 ]`? Because that's pretty standard in my (admittedly very basic) bash.


Instead of

somecommand

if [ $? -ne 0 ]; then echo "it failed"; fi

the parent commenter presumably wants to see

if ! somecommand; then echo "it failed"; fi


Or:

    somecommand || echo "it failed"
if it's just one statement. There are some cases where it just looks more natural. For example:

    start_service || log "already started"


> when you see it as a command, it's obvious that any command can be used in an if directly; if is just checking the exit code

One of the best days of my life


test is [


Indeed, "test" is exactly like "[" except that it doesn't check that its last argument is a "]".


For some reason I've always been amused by "which [". The idea of 'punctuation' being a command or a filename is something that threw me.




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: