How to use shelljs

Comprehensive shelljs code examples:

How to use shelljs.error:

19
20
21
22
23
24
25
26
27
28
29


//------------------------------------------------------------------------------
// shell functions
//------------------------------------------------------------------------------
var shellAssert = function () {
    var errMsg = shell.error();
    if (errMsg) {
        throw new Error(errMsg.toString());
    }
}

How to use shelljs.set:

116
117
118
119
120
121
122
123
124
125
}

runOne (props) {
  // https://www.npmjs.com/package/shelljs

  shx.set('-e') // Exit upon error

  const cnt = ('0000' + this.count).slice(-3)
  const name = `${cnt}-${props.boardName}-${props.content}-` +
      `${props.syscalls}-${props.trace}-${props.language}`

How to use shelljs.which:

1
2
3
4
5
6
7
8
9
10
const path = require('path');
const shell = require('shelljs');
const chalk = require('chalk');

if (shell.which('node')) {
  const NODE_COMMAND_PATH = shell.which('node').stdout;
  const NODE_PATH = path.join(NODE_COMMAND_PATH, '../../lib/node_modules');
  console.log(chalk.yellow('\r\n Please execute flow command, Add global easywebpack-cli to $NODE_PATH'));
  console.log(chalk.green('\r\n1. Use vim command to open bash_profile file: \r\n\r\n') + chalk.blue('vim ~/.bash_profile'));
  console.log(chalk.green('\r\n2. Use export command to add NODE_PATH in bash_profile: \r\n\r\n') + chalk.blue(`export NODE_PATH=${NODE_PATH}:$NODE_PATH`));

How to use shelljs.tempdir:

56
57
58
59
60
61
62
63
64
65
let workDir;
try {
    workDir = workDirs.pop();
    if (!workDir) {
        workDir = join(
            index === 0 ? join(tempdir(), "spaced folder") : tempdir(),
            `pwt_test_${Math.round(Math.random() * 10000)}`
        );
        mkdir("-p", workDir);
    }

How to use shelljs.pushd:

21
22
23
24
25
26
27
28
29
30

require('dotenv').config({
  path: `./deployments/devnet-${nextDevnetId}/.env`
})

shell.pushd(`./deployments/devnet-${nextDevnetId}`)
shell.exec(`terraform workspace new devnet-${nextDevnetId}`)
shell.popd()

console.log('📍Executing terraform init...')

How to use shelljs.popd:

23
24
25
26
27
28
29
30
31
32
  path: `./deployments/devnet-${nextDevnetId}/.env`
})

shell.pushd(`./deployments/devnet-${nextDevnetId}`)
shell.exec(`terraform workspace new devnet-${nextDevnetId}`)
shell.popd()

console.log('📍Executing terraform init...')
shell.exec(`terraform -chdir=./deployments/devnet-${nextDevnetId} init`, {
  env: {

How to use shelljs.default:

91
92
93
94
95
96
97
98
99
100
var bindings = {
    container: (0, awilix_1.asValue)(container),
    isProduction: (0, awilix_1.asValue)(process.env.NODE_ENV === 'production'),
    isDebug: (0, awilix_1.asFunction)(function (immunxConfig) { return immunxConfig.debug; }),
    shell: (0, awilix_1.asFunction)(function (isDebug) {
        shelljs_1.default.config.silent = isDebug ? false : true;
        return shelljs_1.default;
    }).singleton(),
    axios: (0, awilix_1.asValue)(axios_1.default),
    prompt: (0, awilix_1.asValue)(prompts_1.default),

How to use shelljs.test:

652
653
654
655
656
657
658
659
660
661

const DOCS_RULES_DIR = path.join(DOCS_SRC_DIR, "rules");
const RULE_VERSIONS_FILE = path.join(DOCS_SRC_DIR, "_data/rule_versions.json");

// Set up rule version information
let versions = test("-f", RULE_VERSIONS_FILE) ? JSON.parse(cat(RULE_VERSIONS_FILE)) : {};

if (!versions.added) {
    versions = {
        added: versions,

How to use shelljs.grep:

50
51
52
53
54
55
56
57
58
59
60
}


// Get valid target from framework/project.properties
module.exports.get_target = function() {
    function extractFromFile(filePath) {
        var target = shelljs.grep(/\btarget=/, filePath);
        if (!target) {
            throw new Error('Could not find android target within: ' + filePath);
        }
        return target.split('=')[1].trim();

How to use shelljs.find:

663
664
665
666
667
668
669
670
671
    };
}

// 1. Update rule meta data by checking rule docs - important to catch removed rules
echo("> Updating rule version meta data (Step 1)");
const ruleDocsFiles = find(DOCS_RULES_DIR);

ruleDocsFiles.forEach((filename, i) => {
    if (test("-f", filename) && path.extname(filename) === ".md") {

How to use shelljs.pwd:

25
26
27
28
29
30
31
32
33
34
const extVersion = utils.getExtVersion();
const extName = utils.getExtName();
const extString = `${extName}_${extVersion}`;

shell.config.silent = true;
let pwd = shell.pwd();
const rootDir = pwd.match(/[^\\|\/]*$/)[0];
shell.config.silent = false;

// beginning the prompts

How to use shelljs.touch:

2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
    entries.forEach(entry => {
        assert(entry.changed === false, `the entry for ${entry.key} is initially unchanged`);
    });

    // this should result in a changed entry
    shell.touch(goodFile);
    fileCache = fCache.createFromFile(cacheLocation);
    assert(fileCache.getFileDescriptor(badFile).changed === false, `the entry for ${badFile} is unchanged`);
    assert(fileCache.getFileDescriptor(goodFile).changed === true, `the entry for ${goodFile} is changed`);
});

How to use shelljs.ShellString:

90
91
92
93
94
95
96
97
98
99
    },
    files: [aotEntryFile],
    include: undefined,
    exclude: [filesInfo.distFolder, filesInfo.exampleFolder, 'node_modules']
};
sh.ShellString(JSON.stringify(newTsconfigJson, null, 4)).to(filesInfo.tsconfigJsonPath);
sh.exec('npx ngc -p tsconfig.json');

// delete the aotEntry dummy file 
sh.rm('-f', aotEntryFile);

How to use shelljs.ls:

0
1
2
3
4
5
6
7
8
9
const fs = require('fs');
const sh = require('shelljs');

const { fileExists, dirExists } = require('./utils');

const srcContents = sh.ls('src');

// We don't want to commit built files, so it is useful to have a `clean` script which deletes them if they exist.
// However, Reactochart is built in the root directory
// (so that modules may be required with eg. `require('reactochart/LineChart')`).

How to use shelljs.cat:

80
81
82
83
84
85
86
87
88
89
90
  'utf-8',
);


fs.writeFileSync(
  'packages/react-native/React/Base/RCTVersion.m',
  cat('scripts/versiontemplates/RCTVersion.m.template')
    .replace('${major}', `@(${major})`)
    .replace('${minor}', `@(${minor})`)
    .replace('${patch}', `@(${patch})`)
    .replace(

How to use shelljs.config:

39
40
41
42
43
44
45
46
47
48
      expect(execSpy).toHaveBeenCalledOnceWith(exampleCommand, jasmine.any(Function));
    });
});

it('should set the shell config to silent if provided, then set to false after execution', () => {
  let { silent } = shell.config;

  execSpy = spyOn(shell, 'exec').and.callFake((command, func) => {
    func(0, { command }, undefined);
  });

How to use shelljs.mv:

491
492
493
494
495
496
497
498
499
500
  path.join('ui', 'src/pages', indexFileName),
  customNextIndex,
  'utf8'
);

sh.mv(
  path.join('ui', 'src/pages', '_app.tsx'),
  path.join('ui', 'src/pages', '_app.page.tsx')
);
sh.mv(

How to use shelljs.exit:

42
43
44
45
46
47
48
49
50
51
if (isWin) {
  shell.echo(`ℹ️ Skipping translations compilation on Windows.`);
  shell.echo(
    `ℹ️ Pull Requests are welcome to add support for "msgcat" on Windows!`
  );
  shell.exit(0);
} else {
  msgcat = shell.exec('which msgcat 2>/dev/null', { silent: true }).stdout;
  if (!msgcat) {
    msgcat = shell.exec('find /usr -name "msgcat" -print -quit 2>/dev/null', {

How to use shelljs.sed:

228
229
230
231
232
233
234
235
236
237
// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
  shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
  shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
  shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');

// Run external tool synchronously

How to use shelljs.cd:

50
51
52
53
54
55
56
57
58
59
  cleanInit()

  await cloneFiles()

  shell.echo('\nCleaning files.')
  shell.cd(path.resolve(__dirname))
  shell.rm('-rf', cacheDir)

  shell.echo('\ndone.')
}

How to use shelljs.mkdir:

74
75
76
77
78
79
80
81
82
83

if (!isProgrammingLanguageExtension) {
  continue
}

shelljs.mkdir('-p', path.join(pathToExtensionBundles, extensionName))
shelljs.exec(
  `cp ${path.join(bundlePath, 'package.json')} ${path.join(pathToExtensionBundles, extensionName, 'package.json')}`
)
shelljs.exec(

How to use shelljs.rm:

13
14
15
16
17
18
19
20
21
22
// Sounds dangerous, but any files in root which share a name with src would have been overwritten by the build anyway.

srcContents.forEach(fileOrDir => {
  if (fileExists(`src/${fileOrDir}`) && fileExists(`./${fileOrDir}`)) {
    console.log(`deleting file ./${fileOrDir}`);
    sh.rm(`./${fileOrDir}`);
  } else if (dirExists(`src/${fileOrDir}`) && dirExists(fileOrDir)) {
    console.log(`deleting directory ./${fileOrDir}`);
    sh.rm('-rf', `./${fileOrDir}`);
  }

How to use shelljs.cp:

186
187
188
189
190
191
192
193
194
const files = getLocaleSourceCatalogFiles(locale);

if (files.length === 1) {
  // For languages with a single source ("en", "pseudo_LOCALE"),
  // don't concatenate anything.
  const cpResult = shell.cp(
    path.join(getLocalePath(locale), files[0]),
    path.join(getLocalePath(locale), 'messages.po')
  );

How to use shelljs.echo:

4
5
6
7
8
9
10
11
12
13
const shell = require('shelljs')
const path = require('path')
const fs = require('fs-extra')

if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git')
  shell.exit(1)
}

const cacheDir = 'pdf'

How to use shelljs.exec:

24
25
26
27
28
29
30
31
32
33

signale.info(`Did not find an existing code-intel-extensions bundles matching revision ${revision}.`)

signale.pending('Fetching code intel extensions bundles...')

const result = shelljs.exec(`curl -OLs https://github.com/sourcegraph/${bundlesRepoName}/archive/${revision}.zip`)

if (result.code !== 0) {
  console.error('Curl command failed with exit code:', result.code)
  console.error('Error message:', result.stderr)