How to run bash scripts with yarn via a separate file?

Viewed 9722

I have a Node/React project and in my package.json if I want to run some simple scripts I might do something like this:

{
  "scripts": {
    "prep": "cp -r this/sub-directory/path another/sub-directory/path"
  },
}

And then yarn prep to execute it.

However in this case I have a lot of commands, say 5-6 and to put them all on one line in a package.json file would make it difficult to read.

What I would like to do is put them in a separate file and then just call that file. Something like a file named run-script:

#!/bin/bash

echo 'test'

and then in package.json:

{
  "scripts": {
    "prep": "run-script"
  },
}

But that gives me errors obviously, I don't know how to tell it to run the file, what extension it should be, etc. (I'm aware that I can do "prep": "node run-script.js" but in this case I want to do simple things like copy directories and such, not JavaScript things.)


Update [SOLVED]

Both of @roadowl’s solutions were needed.

  1. Run chmod ug+x run-script to set the permissions, and then
  2. Add the current working directory variable ($PWD) in front of where the file is called in package.json:
{
  "scripts": {
    "prep": "$PWD/run-script"
  },
}
2 Answers

I don't see why that wouldn't work. My only advice would be to call it with its full path:

"prep": "/home/me/run-script"

(Where `/home/me' is your home directory, i.e. that which 'echo $HOME' prints).

And, in addition, of course make sure run-script is executable by doing:

chmod ug+x run-script

There is no need to set an absolute path, a relative URL works fine, but bear in mind that if you are referring to the same folder, don't forget to prepend './'

For example:

"scripts": {
   ...
   "foo": "./foo.sh",
   ...
}

Also, as Roadowl suggested, you have to set execution permissions

Related