wierd if statement
oceanMIH opened this issue · comments
hi guys, would someone please explain the follow:
- in the terminal, the following code is NOT OK:
if ;then echo yes;fi
-bash: syntax error near unexpected token `;'
- but if i run it in a shell file, the code is OK, why?
cat tmp.sh
if $1 ;then echo yes;fi
./tmp.sh
yes
I test these on bash version: 5.0.0(1)-release, 4.4.20(1)-release
For the love of Bash and own safety, please do quote variables; The extension is to be .bash
, not .sh
, or go without any. Of course not forget to start a Bash script with this to make it run right:
#!/usr/bin/env bash
Anyways, the 1st shall've "${1:-""}"
to be the same, no parsing errors then. Why? if ; then
must have something between if
and ;
and you may just put safe :
or simple true
to bypass it, though it is sort of pointless in this case and should be like if [[ -n "${1:-""}" ]]; then
if want to just make sure something is in "${1:-""}"
. On echo
, please prefer to use more predictable safe printf
instead or upgrade echo
by this simple function at the start of a script:
echo() { printf -- '%s\n' "${*:-""}"; }