Bash
Functions
namename prints the basename without extension
ext prints extension of a file, including “.”
function namename()
{
local name=${1##*/}
local name0="${name%.*}"
echo "${name0:-$name}"
}
function ext()
{
local name=${1##*/}
local name0="${name%.*}"
local ext=${name0:+${name#$name0}}
echo "${ext:-.}"
}
Commands
CTRL Key Bound
Ctrl + _= undoCtrl + @= set markCtrl + a= Jump to the start of the lineCtrl + b= Move back a charCtrl + c= Terminate the commandCtrl + d= Delete character under the cursorCtrl + e= Jump to the end of the lineCtrl + f= Move forward a charCtrl + k= Delete from cursor to EOLCtrl + l= Clear the screenCtrl + n= select the next command in historyCtrl + p= select the previous command in historyCtrl + r= Search the history backwardsCtrl + R= Search the history backwards with multi occurrenceCtrl + t= drag character before cursor over the one under the cursorCtrl + u= Delete backward from cursorCtrl + v= Insert next character verbatimCtrl + w= kill word before cursorCtrl + x= kill backward to the beginning of lineCtrl + xx= Move between EOL and current cursor positionCtrl + x @= Show possible hostname completionsCtrl + y= paste the text at top of the kill#ringCtrl + z= Suspend/ Stop the command
ALT Key Bound
Alt + ''<''= Move to the first line in the historyAlt + ''>''= Move to the last line in the historyAlt + ?= Show current completion listAlt + *= Insert all possible completionsAlt + /= Attempt to complete filenameAlt + .= Yank last argument to previous commandAlt + b= Move backwardAlt + c= Capitalize the wordAlt + d= Delete wordAlt + f= Move forwardAlt + l= Make word lowercaseAlt + n= Search the history forwards non=incrementalAlt + p= Search the history backwards non=incrementalAlt + r= Recall commandAlt + t= Move words aroundAlt + u= Make word uppercaseAlt + backspace= Delete backward from cursor
Meta Key Bound
Meta usually corresponds to the Esc key
M + f= move forward to the end of next wordM + b= move backward to the start of current or previous wordM + c= capitalize current wordM + d= kill current wordM + l= downcase current wordM + t= drag the word before cursor over the one under the cursorM + u= uppercase current wordM + y= rotate the kill=ring
More Special Keybindings
Here “2T” means Press TAB twice
$ 2T= All available commands(common)$ (string)2T= All available commands starting with (string)$ /2T= Entire directory structure including Hidden one$ 2T= Only Sub Dirs inside including Hidden one$ *2T= Only Sub Dirs inside without Hidden one$ ~2T= All Present Users on system from “/etc/passwd”$ $2T= All Sys variables$ @2T= Entries from “/etc/hosts”$ =2T= Output like ls or dirCtrl + v Ctrl + m= Insert a newline control character
Scripts
Remove the extensions from multiple files
find -type f -name "name.ext" | while read i; do mv $i $i%.ext; done
Rot13 Encryption
In a file:
cat "$@" | tr 'a-zA-Z' 'n-za-mN-Z-A-M'
exit 0
Rename multiple files
for files in $(ls .); do
newname=`echo $files | sed 's/oldtext/newtext/g'`;
mv $files $newname;
done
Syntax
Various Bash syntax rules
${#variable}= Variable string lengthvariable=$(<file)= Save in variable the content of a file: > file= Delete the content of file (likecat /dev/null). If it didn’t exist, creates a new, empty onels -l {b*, aa*, cc*}= Multiple selection. Select all files matching theb*,aa*andcc*patterns in a singlelsrun- mkdir -p
{aaa,bbb/ccc,def,parent{subdir1,subdir2,subdir3},ppp}= Make whole tree of directories with the same multiple selection syntax as above cmd1 (<cmd2) (<cmd3) (<cmd4)= Send the stdout of the various commands to the preceding one, from right to left. For example:sort (<ls /bin) (<ls /usr/bin) (<ls /opt), which will send the list of files in those 3 directories to sortvariable=${1:-123}= Givesvariablethe value of the first parameter ($1). If this is empty, assign to it123${variable##*.} = Corresponds to everything there is in the variable after the period. Generally used with filenames to obtain just the extension${variable%%.*} = Corresponds to everything there is in the variable before the period. Great to obtain filenames without the extension$RANDOM= Gives back a semi-random number between 0 and 32767[[ string =~ pattern ]]= Returns true if string matches pattern (according to ERE, Extended Regular Expressions). Only for bash >=3.0<<-END= Usually<<ENDsends the output as it is. With an added-it strips any tab (but still includes whitespaces)declare= Declares various variables: with-a, an array,-Aan associative array,-ian integer,-la string with only lowercase characters,-ra read-only variable,-ua string with only uppercase charactersshopt -s extglob= Enables extended globs^aaa^bbb= Substitutesaaawithbbbin the last executed command on the terminal. Useful to rerun the same command but with different argumentsecho ${PIPESTATUS[@]}= Find out all the exit codes of the previously piped commandsrm * !("filename")= Remove all files in current directory but forfilename. Wildcards can be used to specify the matching like*.extorfilenames?or[!abcde]
Bash History
How to use and navigate through Bash’s history
!!= Rerun the last executed command!*= Represent all the arguments of the last executed command!$= Corresponds to the very last argument of the last executed command!!:2-3= Corresponds to the list of arguments going from the second to the third of the last executed command. It can also be used like!!:2-$to represent every argument from the second to the last.!n= Run the command at lineninbash_history!cmd:p= Show the last timecmdwas executed, with all its arguments and parameters!cmd= Rerun, with same arguments and parameters, last execution ofcmd!!:gs/oldarguments/newarguments= Rerun last executed command substitutingoldargumentswithnewarguments
Bash Redirection
Partly copied/modified from bash-redirections-cheat-sheet
cmd > file= redirect stdout to file. Alsocmd 1> filecmd 2> file= redirect stderr to filecmd >> file= append stdout to filecmd &> file= redirect stdout and stderr to file. Alsocmd > file 2>&1cmd <<< "string"= redirect a single line of text to the stdin ofcmdexec 2> file= redirect stderr of all commands to a file foreverexec 3< file= open a file for reading using a custom file descriptorexec 3> file= open a file for writing usint a custom file descriptorexec 3<> file= open a file for reading and writing using a custom file descriptorexec 3>&-= close a file descriptorexec 4>&3= make file descriptor 4 to be a copy of 3. Withexec 4>&3-also close 3echo "abc" >&3= write to custom file descriptor 3cat <&3= read from custom file descriptor 3(cmd1; cmd2) > file= redirecto stdout from multiple commands to a file (using a sub-shell). Or with{ cmd1; cmd2 } > file, without using a sub-shellexec 3<> /dev/tcp/host/port= open a tcp connection to host:port. With/dev/udp/host/portopens a udp connectioncmd1 |& cmd2= redirect stdout and stderr ofcmd1to stdin ofcmd2. This is for bash 4.0+ only, for older versions usecmd1 2>&1 | cmd2exec {filew}> file= open a file for writing using a named file descriptor called {filew}. Bash 4.1+ onlycmd 3>&1 1>&2 2>&3= swap stdout and stderr of cmdcmd > >(cmd1) 2> >(cmd2)= send stdout of cmd to cmd1 and stderr of cmd to cmd2
Terminal Line Wrapping
To prevent commands to overlap on the prompt, add a \ before every [ and ] in your bash prompt ($PS1)