A
A
Alexey Bely2016-11-04 20:43:21
bash
Alexey Bely, 2016-11-04 20:43:21

How to specify multiple conditions with logical OR for if that contain *?

There is a script which should accept the arguments entered by the user. In it, you need to specify several variables in the if in the if then else loop so that their beginning is like qwerty*, asddfg*, etc., that is, after a certain specified set of characters, you can substitute any and if will consider this a positive answer.
In general, something like this:

if 
then
echo error
else 
echo success
fi

As soon as I did not try, what's the trouble, I do not understand. If you specify only one condition, then everything works.
Is it possible to somehow rewrite, the main thing is that you can set several conditions.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
RPG, 2016-11-04
@whitest

|| separates expressions, $1 != video* is an expression, but just audio* is not.
But I would solve this problem through case:

case $1 in
video*|audio*|pic*) echo ok;;
*) echo error;;
esac

A
abcd0x00, 2016-11-05
@abcd0x00

#!/bin/bash

test_parameter()
{
    echo "$1" | grep -q '\(video\|audio\|pic\)\*'
}

if ! test_parameter "$1"; then
    echo error
else
    echo success
fi

exit 0

Conclusion
[[email protected] sh]$ ./t.sh video
error
[[email protected] sh]$ ./t.sh video*
success
[[email protected] sh]$ ./t.sh audio
error
[[email protected] sh]$ ./t.sh audio*
success
[[email protected] sh]$ ./t.sh x
error
[[email protected] sh]$

Another option (everything on functions)
#!/bin/bash

error()
{
   echo "error: $1" 1>&2
}

ok()
{
   echo "success: $1" 1>&2
}

test_parameter()
{
    echo "$1" | grep -q '\(video\|audio\|pic\)\*'
}

main()
{
    if ! test_parameter "$1"; then
        error "incorrect parameter: \"$1\""
    else
        ok "parameter is correct"
    fi
}

main "[email protected]" || exit 1

exit 0

Conclusion
[[email protected] sh]$ ./t.sh 
error: incorrect parameter: ""
[[email protected] sh]$ ./t.sh video
error: incorrect parameter: "video"
[[email protected] sh]$ ./t.sh video*
success: parameter is correct
[[email protected] sh]$ ./t.sh audio
error: incorrect parameter: "audio"
[[email protected] sh]$ ./t.sh audio*
success: parameter is correct
[[email protected] sh]$ ./t.sh pic
error: incorrect parameter: "pic"
[[email protected] sh]$ ./t.sh pic*
success: parameter is correct
[[email protected] sh]$ ./t.sh x
error: incorrect parameter: "x"
[[email protected] sh]$

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question