0
# Shebang Regex
1
2
Shebang Regex provides a simple regular expression for matching Unix shebang lines at the beginning of files. It exports a single RegExp object that can be used to test for the presence of shebang lines and extract both the complete shebang line and the command portion.
3
4
## Package Information
5
6
- **Package Name**: shebang-regex
7
- **Package Type**: npm
8
- **Language**: JavaScript (ES module)
9
- **Installation**: `npm install shebang-regex`
10
11
## Core Imports
12
13
```javascript
14
import shebangRegex from 'shebang-regex';
15
```
16
17
For CommonJS (not officially supported, package is ES module only):
18
19
```javascript
20
// Use dynamic import for CommonJS environments
21
const { default: shebangRegex } = await import('shebang-regex');
22
```
23
24
## Basic Usage
25
26
```javascript
27
import shebangRegex from 'shebang-regex';
28
29
const scriptContent = '#!/usr/bin/env node\nconsole.log("Hello world");';
30
31
// Test if string starts with a shebang
32
const hasShebang = shebangRegex.test(scriptContent);
33
// Result: true
34
35
// Extract shebang information
36
const match = shebangRegex.exec(scriptContent);
37
// match[0]: '#!/usr/bin/env node' (complete shebang line)
38
// match[1]: '/usr/bin/env node' (command portion)
39
40
console.log('Full shebang:', match[0]);
41
console.log('Command:', match[1]);
42
```
43
44
## Capabilities
45
46
### Shebang Detection
47
48
Test whether a string begins with a shebang line using the standard RegExp test method.
49
50
```typescript { .api }
51
/**
52
* Regular expression for matching Unix shebang lines
53
* Pattern: /^#!(.*)/
54
* Tests for lines starting with #! and captures the command portion
55
* Note: Only matches shebang at the very beginning of the string
56
*/
57
declare const shebangRegex: RegExp;
58
59
// Standard RegExp.prototype.test method
60
shebangRegex.test(string: string): boolean;
61
```
62
63
**Usage Example:**
64
65
```javascript
66
import shebangRegex from 'shebang-regex';
67
68
// Test various inputs
69
shebangRegex.test('#!/bin/bash'); // true
70
shebangRegex.test('#!/usr/bin/env python'); // true
71
shebangRegex.test('# This is a comment'); // false
72
shebangRegex.test('console.log("hello");'); // false
73
```
74
75
### Shebang Extraction
76
77
Extract shebang information using the standard RegExp exec method.
78
79
```typescript { .api }
80
/**
81
* Execute search for shebang match and extract components
82
* @param string - The string to search
83
* @returns RegExpExecArray | null - Match array with captured groups or null
84
* - [0]: Complete shebang line (e.g., "#!/usr/bin/env node")
85
* - [1]: Command portion (e.g., "/usr/bin/env node")
86
* Note: Returns null if no shebang found at start of string
87
*/
88
shebangRegex.exec(string: string): RegExpExecArray | null;
89
```
90
91
**Usage Examples:**
92
93
```javascript
94
import shebangRegex from 'shebang-regex';
95
96
// Extract from Node.js script
97
const nodeScript = '#!/usr/bin/env node\nprocess.exit(0);';
98
const nodeMatch = shebangRegex.exec(nodeScript);
99
console.log(nodeMatch[0]); // '#!/usr/bin/env node'
100
console.log(nodeMatch[1]); // '/usr/bin/env node'
101
102
// Extract from Python script
103
const pythonScript = '#!/usr/bin/python3\nprint("hello")';
104
const pythonMatch = shebangRegex.exec(pythonScript);
105
console.log(pythonMatch[0]); // '#!/usr/bin/python3'
106
console.log(pythonMatch[1]); // '/usr/bin/python3'
107
108
// No match case
109
const regularCode = 'const x = 42;';
110
const noMatch = shebangRegex.exec(regularCode);
111
console.log(noMatch); // null
112
```
113
114
### Standard RegExp Methods
115
116
Since shebangRegex is a standard RegExp object, it provides all standard RegExp methods and properties.
117
118
```typescript { .api }
119
/**
120
* All standard RegExp methods and properties are available:
121
*/
122
123
// String matching methods
124
shebangRegex.test(str: string): boolean;
125
shebangRegex.exec(str: string): RegExpExecArray | null;
126
127
// RegExp properties
128
readonly shebangRegex.source: string; // '^#!(.*)'
129
readonly shebangRegex.flags: string; // ''
130
readonly shebangRegex.global: boolean; // false
131
readonly shebangRegex.ignoreCase: boolean; // false
132
readonly shebangRegex.multiline: boolean; // false
133
shebangRegex.lastIndex: number; // 0 (mutable for global regexes)
134
135
// Convert to string representation
136
shebangRegex.toString(): string; // '/^#!(.*)/'
137
```
138
139
## Types
140
141
```typescript { .api }
142
/**
143
* The exported shebangRegex is a standard JavaScript RegExp object
144
* with the pattern /^#!(.*)/ for matching Unix shebang lines
145
*
146
* Pattern explanation:
147
* - ^ : Match start of string
148
* - #! : Match literal shebang characters
149
* - (.*) : Capture group for the command portion
150
*/
151
declare const shebangRegex: RegExp;
152
153
export default shebangRegex;
154
```
155
156
## Common Use Cases
157
158
### CLI Tool File Detection
159
160
```javascript
161
import shebangRegex from 'shebang-regex';
162
import { readFileSync } from 'fs';
163
164
function isExecutableScript(filePath) {
165
const content = readFileSync(filePath, 'utf8');
166
return shebangRegex.test(content);
167
}
168
169
function getScriptInterpreter(filePath) {
170
const content = readFileSync(filePath, 'utf8');
171
const match = shebangRegex.exec(content);
172
return match ? match[1] : null;
173
}
174
```
175
176
### Build Tool Integration
177
178
```javascript
179
import shebangRegex from 'shebang-regex';
180
181
function processScriptFiles(files) {
182
return files.map(file => ({
183
path: file.path,
184
content: file.content,
185
isExecutable: shebangRegex.test(file.content),
186
interpreter: shebangRegex.exec(file.content)?.[1] || null
187
}));
188
}
189
```
190
191
### Template Processing
192
193
```javascript
194
import shebangRegex from 'shebang-regex';
195
196
function stripShebang(code) {
197
return code.replace(shebangRegex, '');
198
}
199
200
function replaceShebang(code, newInterpreter) {
201
if (shebangRegex.test(code)) {
202
return code.replace(shebangRegex, `#!${newInterpreter}`);
203
}
204
return `#!${newInterpreter}\n${code}`;
205
}
206
```