Boolean operators ( &&, -a, ||, -o ) in Bash

后端 未结 2 1362
礼貌的吻别
礼貌的吻别 2020-12-04 08:27

Can someone please explain the difference between the &&, ||, -a, and -o Unix operators?

What are the res

2条回答
  •  情歌与酒
    2020-12-04 09:12

    -a and -o are the older and/or operators for the test command. && and || are and/or operators for the shell. So (assuming an old shell) in your first case,

    [ "$1" = 'yes' ] && [ -r $2.txt ]
    

    The shell is evaluating the and condition. In your second case,

    [ "$1" = 'yes' -a $2 -lt 3 ]
    

    The test command (or builtin test) is evaluating the and condition.

    Of course in all modern or semi-modern shells, the test command is built in to the shell, so there really isn't any or much difference. In modern shells, the if statement can be written:

    [[ $1 == yes && -r $2.txt ]]
    

    Which is more similar to modern programming languages and thus is more readable.

提交回复
热议问题