-
Notifications
You must be signed in to change notification settings - Fork 283
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #112 from llagerlof/shell_history
Add executed commands to shell history
- Loading branch information
Showing
2 changed files
with
61 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import fs from 'fs'; | ||
import os from 'os'; | ||
import path from 'path'; | ||
|
||
// Function to get the history file based on the shell | ||
function getHistoryFile(): string | null { | ||
const shell = process.env.SHELL || ''; | ||
const homeDir = os.homedir(); | ||
|
||
switch (path.basename(shell)) { | ||
case 'bash': | ||
case 'sh': | ||
return path.join(homeDir, '.bash_history'); | ||
case 'zsh': | ||
return path.join(homeDir, '.zsh_history'); | ||
case 'fish': | ||
return path.join(homeDir, '.local', 'share', 'fish', 'fish_history'); | ||
case 'ksh': | ||
return path.join(homeDir, '.ksh_history'); | ||
case 'tcsh': | ||
return path.join(homeDir, '.history'); | ||
default: | ||
return null; | ||
} | ||
} | ||
|
||
// Function to get the last command from the history file | ||
function getLastCommand(historyFile: string): string | null { | ||
try { | ||
const data = fs.readFileSync(historyFile, 'utf8'); | ||
const commands = data.trim().split('\n'); | ||
return commands[commands.length - 1]; | ||
} catch (err) { | ||
// Ignore any errors | ||
return null; | ||
} | ||
} | ||
|
||
// Function to append the command to the history file if it's not the same as the last command | ||
export function appendToShellHistory(command: string): void { | ||
const historyFile = getHistoryFile(); | ||
if (historyFile) { | ||
const lastCommand = getLastCommand(historyFile); | ||
if (lastCommand !== command) { | ||
fs.appendFile(historyFile, `${command}\n`, (err) => { | ||
if (err) { | ||
// Ignore any errors | ||
} | ||
}); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters