or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-shx

Portable Shell Commands for Node - cross-platform wrapper around ShellJS for npm package scripts

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/shx@0.4.x

To install, run

npx @tessl/cli install tessl/npm-shx@0.4.0

0

# shx

1

2

shx is a wrapper around ShellJS Unix commands, providing an easy solution for simple Unix-like, cross-platform commands in npm package scripts. It enables running shell commands that work consistently across Windows, macOS, and Linux systems, solving the problem of platform-specific shell command differences in Node.js development workflows.

3

4

## Package Information

5

6

- **Package Name**: shx

7

- **Package Type**: npm

8

- **Language**: JavaScript (ES6+ with Babel)

9

- **Installation**: `npm install shx --save-dev`

10

- **Repository**: https://github.com/shelljs/shx

11

12

## Core Imports

13

14

For programmatic usage:

15

16

```javascript

17

import { shx } from 'shx';

18

```

19

20

CommonJS:

21

22

```javascript

23

const { shx } = require('shx/lib/shx');

24

```

25

26

Note: shx is primarily designed as a CLI tool, but the core function can be imported directly from the package for programmatic use.

27

28

## Basic Usage

29

30

### Command Line Usage

31

32

```bash

33

# Install globally for command line usage

34

npm install -g shx

35

36

# Basic file operations

37

shx ls # List files

38

shx mkdir build # Create directory

39

shx cp src/file.js build/ # Copy files

40

shx rm -rf build # Remove directory recursively

41

shx echo "Hello World" # Output text

42

43

# With options

44

shx --silent ls nonexistent # Suppress error output

45

shx --verbose cp file.js dest/ # Verbose logging

46

shx --negate test -d mydir # Negate exit code

47

```

48

49

### npm Package Scripts

50

51

Most common usage in `package.json`:

52

53

```json

54

{

55

"scripts": {

56

"clean": "shx rm -rf build dist",

57

"prebuild": "shx mkdir -p build && shx cp -r src/* build/",

58

"postbuild": "shx echo \"Build complete!\"",

59

"test:cleanup": "shx rm -rf coverage && shx rm *.log"

60

}

61

}

62

```

63

64

## Architecture

65

66

shx is a cross-platform CLI wrapper around ShellJS commands with several key architectural components:

67

68

- **CLI Entry Point** (`cli.js`): Handles command-line argument parsing and stdin detection, passes execution to the core shx function

69

- **Core Command Processor** (`shx.js`): Main execution engine that validates commands, loads plugins, applies options, and executes ShellJS functions

70

- **Configuration System** (`config.js`): Manages exit codes, command blocklists, pipe detection, and plugin loading configuration

71

- **Plugin Architecture**: Extensible plugin system supporting both built-in plugins (true/false) and external plugins via `.shxrc.json`

72

- **Special Command Processing**: Enhanced sed command with Unix-like regex syntax conversion

73

- **Stream Handling**: Automatic stdin detection and processing for pipe-compatible commands

74

75

The architecture ensures that all ShellJS commands work consistently across Windows, macOS, and Linux by normalizing the execution environment and providing cross-platform path and glob handling.

76

77

## Capabilities

78

79

### CLI Binary

80

81

The main shx command-line interface that wraps ShellJS commands with cross-platform compatibility.

82

83

```javascript { .api }

84

// Binary entry point: lib/cli.js

85

// Usage: shx [options] <command> [args...]

86

```

87

88

**Supported Commands:**

89

All ShellJS commands except: `cd`, `pushd`, `popd`, `dirs`, `set`, `exit`, `exec`, `ShellString`

90

91

**Common Commands:**

92

- File operations: `cp`, `mv`, `rm`, `mkdir`, `rmdir`, `ls`, `find`

93

- Text processing: `cat`, `head`, `tail`, `grep`, `sed`, `sort`, `uniq`

94

- File testing: `test`, `which`, `pwd`

95

- Output: `echo`

96

- Built-in: `true`, `false` (via plugin)

97

98

### Global Options

99

100

Options that modify shx behavior across all commands:

101

102

```javascript { .api }

103

// Global shx options (prefix with --)

104

interface ShxOptions {

105

// shx-specific options

106

version: boolean; // Display version information

107

help: boolean; // Show help text

108

negate: boolean; // Flip exit status (0→1, non-zero→0)

109

110

// ShellJS shell.config options (inherited)

111

silent: boolean; // Suppress error output

112

verbose: boolean; // Enable verbose logging

113

noglob: boolean; // Disable glob expansion

114

fatal: boolean; // Exit on first error (not supported in CLI)

115

116

// Command-specific options (passed through to ShellJS)

117

[key: string]: any; // Additional options passed to underlying ShellJS commands

118

}

119

```

120

121

### Programmatic API

122

123

Core function for programmatic usage:

124

125

```javascript { .api }

126

/**

127

* Execute shx command programmatically

128

* @param argv - Command line arguments in process.argv format

129

* @returns Exit code (0 for success, non-zero for errors)

130

*/

131

function shx(argv: string[]): number;

132

```

133

134

**Exit Codes:**

135

136

```javascript { .api }

137

const EXIT_CODES = {

138

SUCCESS: 0, // Successful execution

139

CMD_FAILED: 1, // Command execution failed

140

SHX_ERROR: 27 // shx-specific error (invalid command, etc.)

141

};

142

```

143

144

### Configuration System

145

146

Configuration file support for plugin loading:

147

148

```javascript { .api }

149

// .shxrc.json format

150

interface ShxConfig {

151

plugins: string[]; // Array of plugin names to load

152

}

153

```

154

155

**Example .shxrc.json:**

156

157

```json

158

{

159

"plugins": ["shelljs-plugin-open", "custom-plugin"]

160

}

161

```

162

163

### sed Command Enhancement

164

165

Special regex conversion for Unix-like sed syntax:

166

167

```bash

168

# Unix-style sed syntax (converted internally)

169

shx sed "s/original/replacement/g" filename.txt

170

shx sed -i "s/find/replace/" file.txt

171

172

# Flags supported: g (global), i (case-insensitive)

173

```

174

175

**Important:** Forward slashes `/` in patterns must be escaped as `\/` in shell, or `\\/` in package.json.

176

177

### Input Stream Handling

178

179

Automatic stdin processing for pipe-compatible commands:

180

181

```bash

182

# Commands that support piped input

183

echo "content" | shx grep "pattern"

184

cat file.txt | shx head -5

185

ls | shx sort

186

```

187

188

**Pipe-compatible commands:**

189

- `cat` (minArgs: 1)

190

- `grep` (minArgs: 2)

191

- `head` (minArgs: 1)

192

- `sed` (minArgs: 2)

193

- `sort` (minArgs: 1)

194

- `tail` (minArgs: 1)

195

- `uniq` (minArgs: 1)

196

197

### Plugin System

198

199

Built-in and custom plugin support with automatic loading:

200

201

```javascript { .api }

202

// Built-in true/false plugin (always loaded)

203

function shellTrue(): string; // Returns empty string, exit code 0

204

function shellFalse(): void; // Sets error state, exit code 1

205

```

206

207

**Plugin Loading System:**

208

209

```javascript { .api }

210

/**

211

* Plugin configuration loaded from .shxrc.json in current working directory

212

* Plugins are loaded via require() before command execution

213

*/

214

interface PluginConfig {

215

plugins: string[]; // Array of npm package names to require as plugins

216

}

217

218

/**

219

* Built-in plugin registration (example from true/false plugin)

220

* Uses ShellJS plugin system for command registration

221

*/

222

import plugin from 'shelljs/plugin';

223

224

plugin.register('true', shellTrue, {

225

allowGlobbing: false, // Disable glob expansion for this command

226

wrapOutput: true // Wrap output in ShellString object

227

});

228

229

plugin.register('false', shellFalse, {

230

allowGlobbing: false,

231

wrapOutput: true

232

});

233

```

234

235

**Plugin Loading Process:**

236

1. shx checks for `.shxrc.json` in current working directory

237

2. Attempts to `require()` each plugin listed in the `plugins` array

238

3. Built-in `true/false` plugin is always loaded automatically

239

4. Plugin loading errors throw descriptive error messages

240

241

### Help System

242

243

Dynamic help generation:

244

245

```javascript { .api }

246

/**

247

* Generate help text with available commands and options

248

* @returns Formatted help string

249

*/

250

function help(): string;

251

```

252

253

### Utility Functions

254

255

Output formatting and result handling:

256

257

```javascript { .api }

258

/**

259

* Handle output formatting for ShellJS command results

260

* @param ret - Command result (string, object, or boolean)

261

*/

262

function printCmdRet(ret: any): void;

263

264

/**

265

* Determine if command should read from stdin

266

* @param args - Command arguments array

267

* @returns true if should read stdin, false otherwise

268

*/

269

function shouldReadStdin(args: string[]): boolean;

270

271

/**

272

* Convert Unix-style sed syntax to JavaScript RegExp for ShellJS

273

* @param args - Array of sed command arguments

274

* @returns Array with regex patterns converted to RegExp objects

275

* @throws Error for empty regex patterns

276

*/

277

function convertSedRegex(args: string[]): (string | RegExp)[];

278

```

279

280

### Configuration Constants

281

282

Core configuration values used throughout shx:

283

284

```javascript { .api }

285

// Command blocklist - unsupported ShellJS commands

286

const CMD_BLOCKLIST: string[];

287

288

// Option blocklist - ShellJS options not supported in CLI

289

const OPTION_BLOCKLIST: string[];

290

291

// Configuration file name for plugin loading

292

const CONFIG_FILE: string; // '.shxrc.json'

293

294

// Pipe information for stdin-compatible commands

295

const SHELLJS_PIPE_INFO: {

296

[command: string]: { minArgs: number };

297

};

298

```

299

300

## Error Handling

301

302

### Command Validation

303

304

- Invalid commands return exit code 27 with error message

305

- Blocklisted commands show appropriate warnings

306

- Plugin loading failures throw descriptive errors

307

308

### Input Validation

309

310

- Empty sed patterns are rejected with clear error messages

311

- Missing required arguments are validated before execution

312

- TTY vs pipe detection for stdin handling

313

314

### Cross-Platform Compatibility

315

316

- Consistent behavior across Windows, macOS, and Linux

317

- Proper path handling and glob expansion

318

- Environment-specific optimizations

319

320

## Advanced Usage

321

322

### Complex Package Scripts

323

324

```json

325

{

326

"scripts": {

327

"clean": "shx rm -rf dist coverage *.log",

328

"prebuild": "npm run clean && shx mkdir -p dist/js dist/css",

329

"build": "shx cp -r src/* dist/ && shx echo \"Build complete\"",

330

"test": "shx rm -rf coverage && npm run test:unit",

331

"deploy": "shx test -d dist && shx cp dist/* deploy/ || shx echo \"Deploy failed\""

332

}

333

}

334

```

335

336

### Plugin Configuration

337

338

```json

339

{

340

"plugins": [

341

"shelljs-plugin-open",

342

"@company/custom-shell-plugin"

343

]

344

}

345

```

346

347

### Command Chaining

348

349

```bash

350

# Using shell operators (handled by OS shell)

351

shx mkdir temp && shx cp file.txt temp/ && shx ls temp

352

shx rm -rf old || shx echo "Nothing to clean"

353

354

# In package.json (escape quotes)

355

"script": "shx mkdir build && shx echo \"Directory created\""

356

```

357

358

## Migration from Shell Scripts

359

360

### Windows Compatibility

361

362

Replace platform-specific commands:

363

364

```json

365

{

366

"scripts": {

367

// Instead of: "clean": "rm -rf build" (Unix only)

368

"clean": "shx rm -rf build",

369

370

// Instead of: "copy": "cp -r src dest" (Unix only)

371

"copy": "shx cp -r src dest",

372

373

// Instead of: "mkdir": "mkdir -p build" (Unix only)

374

"mkdir": "shx mkdir -p build"

375

}

376

}

377

```

378

379

### Glob Patterns

380

381

Use double quotes for cross-platform glob support:

382

383

```json

384

{

385

"scripts": {

386

"clean": "shx rm -rf \"build/**/*.js\" \"dist/*.css\"",

387

"copy": "shx cp \"src/**/*.ts\" build/"

388

}

389

}

390

```