[linux] Execute command without keeping it in history

I want to execute some commands but don't want to store them in the command history. So that nobody will be able to search it in the .bash_history file.

Is there any way how to execute bash commands this way?

This question is related to linux bash unix

The answer is

Start your command with a space and it won't be included in the history.

Be aware that this does require the environment variable $HISTCONTROL to be set.

  • Check that the following command returns ignorespace or ignoreboth

    #> echo $HISTCONTROL
  • To add the environment variable if missing, the following line can be added to the bash profile. E.g. %HOME/.bashrc

    export HISTCONTROL=ignorespace

After sourcing the profile again space prefixed commands will not be written to $HISTFILE

In any given Bash session, set the history file to /dev/null by typing:

export HISTFILE=/dev/null

Note that, as pointed out in the comments, this will not write any commands in that session to the history!

Just don't mess with your system administrator's hard work, please ;)

Doodad's solution is more elegant. Simply unset the variable: unset HISTFILE (thanks!)

echo "discreet";history -d $(history 1)

An extension of @John Doe & @user3270492's answer. But, this seems to work for me.

<your_secret_command>; history -d $((HISTCMD-1))

You should not see the entry of the command in your history.

Here's the explanation..

The 'history -d' deletes the mentioned entry from the history.

The HISTCMD stores the command_number of the one to be executed next. So, (HISTCMD-1) refers to the last executed command.

Remove a certain line from Bash history file

You can start your session with

export HISTFILE=/dev/null ;history -d $(history 1)

then proceed with your sneaky doings. Setting the histfile to /dev/null will be logged to the history file, yet this entry will be readily deleted and no traces (at least in the history file) will be shown.

Also, this is non-permanent.

You might consider using a shell without history, like perhaps

/bin/sh << END
   your commands without history

(perhaps /bin/dash or /bin/sash could be more appropriate than /bin/sh)

or even better use the batch utility e.g

batch << EOB
   your commands

The history would then contain sh or batch which is not very meaningful

If you are using zsh you can run:

setopt histignorespace

After this is set, each command starting with a space will be excluded from history.

You can use aliases in .zshrc to turn this on/off:

# Toggle ignore-space. Useful when entering passwords.
alias history-ignore-space-on='\
setopt hist_ignore_space;\
echo "Commands starting with space are now EXCLUDED from history."'

alias history-ignore-space-off='\
unsetopt hist_ignore_space;\
echo "Commands starting with space are now ADDED to history."'

As mentioned by Doodad in comments, unset HISTFILE does this nicely, but in case you also want to also delete some history, do echo $HISTFILE to get the history file location (usually ~/.bash_history), unset HISTFILE, and edit ~/.bash_history (or whatever HISTFILE was - of course it's now unset so you can't read it).

$ echo $HISTFILE       # E.g. ~/.bash_history
$ unset HISTFILE
$ vi ~/.bash_history   # Or your preferred editor

Then you've edited your history, and the fact that you edited it!

You can also use the following command:

echo toto; history -d $(history | sed -n '$s/\s*\([0-9]*\)\s*.*$/\1/p')

I think it's a very portable command.

There are several ways you can achieve this. This sets the size of the history file to 0:


This sets the history file to /dev/null, effectively disabling it:

export HISTFILE=/dev/null

For individual commands, you can prefix the command with a space and it won't be saved in the history file. Note that this requires you have the ignorespace value included in the $HISTCONTROL environment variable (man bash and search for ignorespace for more details).

This is handy if you want to erase all the history, including the fact that you erased all the history!

rm .bash_history;export HISTFILE=/dev/null;exit

You just need to run:
$ set +o history

To see more, run:
$ man set

This command might come in handy. This will not record the command that is executed

history -d $((HISTCMD-1)) && <Your Command Here>

Questions with linux tag:

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt? How to post raw body data with curl? Copy Files from Windows to the Ubuntu Subsystem How to use local docker images with Minikube? Can Windows Containers be hosted on linux? gradlew command not found? ssh connection refused on Raspberry Pi Composer: file_put_contents(./composer.json): failed to open stream: Permission denied Curl : connection refused boto3 client NoRegionError: You must specify a region error only sometimes gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now sudo: docker-compose: command not found How to upgrade pip3? How can I remove jenkins completely from linux Linux Command History with date and time MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded" What is difference between arm64 and armhf? How to redirect output of systemd service to a file Retrieve last 100 lines logs Failed to find Build Tools revision 23.0.1 Run an Ansible task only when the variable contains a specific string What does `set -x` do? How to edit a text file in my terminal Starting a shell in the Docker Alpine container How to run SUDO command in WinSCP to transfer files from Windows to linux Fail during installation of Pillow (Python module) in Linux How to install Android SDK on Ubuntu? How do I delete virtual interface in Linux? What is the default root pasword for MySQL 5.7 Docker command can't connect to Docker daemon How to find files modified in last x minutes (find -mmin does not work as expected) Can I use Homebrew on Ubuntu? Pycharm and sys.argv arguments Ubuntu: OpenJDK 8 - Unable to locate package Fork() function in C Amazon Linux: apt-get: command not found Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable Ubuntu: Using curl to download an image Docker error response from daemon: "Conflict ... already in use by container" Curl command without using cache Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

Questions with bash tag:

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal? Copy Files from Windows to the Ubuntu Subsystem Docker: How to use bash with an Alpine based docker image? How to print / echo environment variables? Passing bash variable to jq gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now How to check if an environment variable exists and get its value? docker entrypoint running bash script gets "permission denied" Copy Paste in Bash on Ubuntu on Windows How to set env variable in Jupyter notebook How do I disable Git Credential Manager for Windows? How to set aliases in the Git Bash for Windows? MINGW64 "make build" error: "bash: make: command not found" Disable beep of Linux Bash on Windows 10 What does `set -x` do? psql: command not found Mac How do I use a regex in a shell script? nodemon not working: -bash: nodemon: command not found How to open google chrome from terminal? Get Environment Variable from Docker Container How to find files modified in last x minutes (find -mmin does not work as expected) How to pass arguments to Shell Script through docker run How to run C program on Mac OS X using Terminal? Curl command without using cache Running a script inside a docker container using shell script Creating an array from a text file in Bash Bash checking if string does not contain other string How to check if a Docker image with a specific tag exist locally? How do I edit $PATH (.bash_profile) on OSX? Raise error in a Bash script how to wait for first command to finish? I just assigned a variable, but echo $variable shows something else What do $? $0 $1 $2 mean in shell script? How to sort a file in-place How to read a .properties file which contains keys that have a period character using Shell script How can I remount my Android/system as read-write in a bash script using adb? How to get ip address of a server on Centos 7 in bash Changing an AIX password via script? How to remove last n characters from a string in Bash? Difference between ${} and $() in Bash List file using ls command in Linux with full path

Questions with unix tag:

Docker CE on RHEL - Requires: container-selinux >= 2.9 What does `set -x` do? How to find files modified in last x minutes (find -mmin does not work as expected) sudo: npm: command not found How to sort a file in-place How to read a .properties file which contains keys that have a period character using Shell script gpg decryption fails with no secret key error Loop through a comma-separated shell variable Best way to find os name and version in Unix/Linux platform Resource u'tokenizers/punkt/english.pickle' not found Unix command to check the filesize How can I get the IP address from NIC in Python? OSError - Errno 13 Permission denied nginx error connect to php5-fpm.sock failed (13: Permission denied) How to get key names from JSON using jq How/When does Execute Shell mark a build as failure in Jenkins? mkdir's "-p" option How to cat <<EOF >> a file containing code? ssh-copy-id no identities found error Setting PATH environment variable in OSX permanently cut or awk command to print first field of first row How do I pause my shell script for a second before continuing? how to set mongod --dbpath SCP Permission denied (publickey). on EC2 only when using -r flag on directories Command to change the default home directory of a user How to split CSV files as per number of rows specified? Assigning the output of a command to a variable Trim leading and trailing spaces from a string in awk Boolean operators ( &&, -a, ||, -o ) in Bash Send password when using scp to copy files from one server to another centos: Another MySQL daemon already running with the same unix socket /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found What does 'stale file handle' in Linux mean? How to run mysql command on bash? How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH? Why does ENOENT mean "No such file or directory"? How do I escape spaces in path for scp copy in Linux? Display exact matches only with grep Configure cron job to run every 15 minutes on Jenkins grep without showing path/file:line Bash command line and input limit Get specific line from text file using just shell script How to run SQL in shell script How to use variables in a command in sed? CURL to pass SSL certifcate and password Running Groovy script from the command line Only mkdir if it does not exist Difference between using "chmod a+x" and "chmod 755" Run ssh and immediately execute command How to check the first character in a string in Bash or UNIX shell?