I'm having trouble passing arguments to my script in bash
. To simplify I made this example that in the same way does not work.
It is supposed that when invoking it as it programa.sh piedra
should give you a message, if it does not match the expected one it gives you an error. But it doesn't work for me, it always says "PAPER":
#!/bin/bash
# programa.sh
if [ "$1"="papel" ]; then
echo -e ""
echo -e "Hola invocaste PAPEL"
echo -e ""
elif [ "$1"="piedra" ]; then
echo -e ""
echo -e "Hola invocaste PIEDRA"
echo -e ""
else
echo -e "Error: solo se soportan los argumento: papel y piedra"
fi
The arguments can go between quotes, in fact this way the is preserved
IFS
and the separation by these is avoided in case the parameter contains a character belonging to theIFS
(tab, space, line break)Your main problem lies in the spaces in the evaluator
[]
That is, instead of
It would have to be
You can safely use the operator
=
because it compares strings inside the evaluator[
.For Bash to understand a token , it checks based on the separators (tab, space, line break), that is, what the variable contains
IFS
. The operator[
would parse based on some token, in this case "=", and to be recognized as such it must be separated from the rest by spaces, otherwise you are just concatenating the argument "$1" to the string "=" and to the string "paper"; that will always evaluate to true, since it's a non-empty string, and will always give you the "Hello, you invoked PAPER" block.Once you put the spaces, your code should look something like this.