Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

wierd if statement #139

Open
oceanMIH opened this issue Apr 15, 2023 · 1 comment
Open

wierd if statement #139

oceanMIH opened this issue Apr 15, 2023 · 1 comment

Comments

@oceanMIH
Copy link

oceanMIH commented Apr 15, 2023

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

@sensemon-san
Copy link

sensemon-san commented Apr 26, 2023

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' "${*:-""}"; }

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants