Inline Bash script to run a command if an argument was passed, and echo a message otherwise

Viewed 42

I'm trying to create a simple inline Bash script (for my package.json scripts) that would:

  • Execute prettier --write [path-passed-in-argument] if an argument was passed
  • Echo "No arguments passed" otherwise

I've tried so many different Stack Overflow suggestions, and nothing has worked.

This is the last thing I tried, to no avail:

package.json

{
  // ...
  "scripts": {
    // ...
    "format:file": "if [ \"$#\" -eq \"0\" ]; then echo \"No arguments supplied\"; else prettier --write $1; fi",
  }
}

Executing this script with no arguments works as expected:

> yarn format:file

yarn run v1.22.19
$ if [ "$#" -eq "0" ]; then echo "No arguments supplied"; else prettier --write $1; fi
No arguments supplied
✨  Done in 0.07s.

However, when executing this script with an argument, e.g. ".", it breaks, because it adds the argument to the end of the statement:

yarn format:file .

yarn run v1.22.19
$ if [ "$#" -eq "0" ]; then echo "No arguments supplied"; else prettier --write $1; fi .
/bin/sh: -c: line 0: syntax error near unexpected token `.'
/bin/sh: -c: line 0: `if [ "$#" -eq "0" ]; then echo "No arguments supplied"; else prettier --write $1; fi .'
error Command failed with exit code 2.
0 Answers
Related