Intro
Bash is IMHO pretty much what makes linux usable on the nitty-gritty level.
Here I'll collect some of the bash tips and tricks I use.
Search history for a particular command
# history | grep ssh-c
ssh-copy-id -i ~/.ssh/id_rsa.pubThis email address is being protected from spambots. You need JavaScript enabled to view it. m -p 1234
Prettify and make the root prompt stand out
Add the following line to your /root/.bashrc, then save the file and restart the terminal to activate the change.
export PS1="\[$(tput bold)$(tput setab 0)$(tput setaf 1)\]\u@\h:\w # \[$(tput sgr0)\]"
The above will make your prompt bold red, so as to make it different from a plain whitish luser-user account.
Take control of the history file
Typing history in the terminal should return a long list of commands you've issued. It can grow pretty long too... Take control with these settings.
Add either, or all, to your /home/$USER/.bashrc file. Save the file after and restart your terminal.
Ignore collecting passwords, ID, uptime, resize, ls, clear and history.
export HISTIGNORE=":pwd:id:uptime:resize:ls:clear:history:"
History will ignore logging any commands beginning with a space as well as any duplicates.
HISTCONTROL=ignorespace:erasedups
or use
HISTCONTROL=ignoreboth
Tag history output with date and time.
HISTTIMEFORMAT="%F %T "
It will produce something like this.
# history
764 2018-11-08 09:50:44 ansible-playbook enable.repo.yml --check
...
Increase amount of history commands
The default is around 500 commands. Sometimes this is not enough.
For user root, add the following to your /root/.bashrc file to increase to 1000 remembered commands. Then save, exit and restart the terminal.
HISTSIZE = 1000
Show the last ten commands in history
# history | tail 10
Read a log file in real time
There may be times when you're troubleshooting and need to see the logs in real-time. Use the below command to achieve this
# tail -f /var/log/httpd/error_access_log
Look for a particular keyword
# tail -f /var/log/httpd/error_access_log | grep 504
Prettify ls for easier reading
Add the below to to your /root/.bashrc file, save, exit and restart the terminal.
ls='ls .color=auto'
Konditionaler
Radera filen file om den existerar med exit statuskod 0
https://riptutorial.com/bash/example/12572/one-liner-test
Kolla om filen finns och isf exportera den.
if [ -f "/usr/bin/wine" ]; then export WINEARCH=win32; fi
Kolla om filen finns och meddela då, annars håll tyst
if [ -e /etc/apt/sources.list.d/*icinga* ]; then echo "icinga repo exists"; else 2>&1; fi
Behövs omstart?
Lista med konditionaler
https://stackoverflow.com/a/21164441
Sources
Various internet sites