Re:Bash [ -z hello ]
by Nyubis on Wednesday June 25, 2014 @01:59PM
(#7945650)
This is pretty awesome, but I don't know if people often phrase their queries like that, and I'm not sure whether it's worth it to start phrasing it like this. It doesn't seem to support more complex bash queries, so I'm not really sure how often this will be used.
[ Parent
| on HN ]
Re:Bash [ -z hello ]
by mattdanger on Wednesday June 25, 2014 @03:01PM
(#7946079)
[ is part of Bash syntax
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"
Re:Bash [ -z hello ]
by JetSpiegel on Wednesday June 25, 2014 @08:06PM
(#7947466)
> 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.
...and perhaps surprisingly also a program sitting on disk.
$ type [
[ is a shell builtin
$ [ 1 -gt 0
bash: [: missing `]'
$ whereis [
/bin/[
$ /bin/[ 1 -gt 0
# successYou got a root shell out of `/bin/[` ? Impressive :)
Hm, which version of [ is that? I get:
$ /usr/bin/[ 1 -gt 0 && echo success
/usr/bin/[: missing `]'
$ /usr/bin/[ 1 -gt 0 ] && echo success
success
(This is from coreutils 8.13-3.5 on Debian GNU/Linux)