User Tools

Site Tools


bash

Bash

Bash Short-Cut

CTRL Key Bound

Ctrl + a - Jump to the start of the line
Ctrl + b - Move back a char
Ctrl + c - Terminate the command
Ctrl + d - Delete from under the cursor
Ctrl + e - Jump to the end of the line
Ctrl + f - Move forward a char
Ctrl + k - Delete to EOL
Ctrl + l - Clear the screen
Ctrl + r - Search the history backwards
Ctrl + R - Search the history backwards with multi occurrence
Ctrl + u - Delete from the cursor to the beginning of the line.
Ctrl + w - Delete from the cursor to the start of the word.
Ctrl + xx - Move between EOL and current cursor position
Ctrl + x @ - Show possible hostname completions
Ctrl + x Ctrl + u - Undo the last changes. Ctrl-_ does the same
Ctrl + y - Pastes text from the clipboard.
Ctrl + z - Suspend/ Stop the command
Ctrl + ] x - Where x is any character, moves the cursor forward to the next occurance of x.

ALT Key Bound

Alt + < - Move to the first line in the history
Alt + > - Move to the last line in the history
Alt + ? - Show current completion list
Alt + * - Insert all possible completions
Alt + / - Attempt to complete filename
Alt + . - Yank last argument to previous command
Alt + b - Move backward
Alt + c - Capitalize the word
Alt + d - Delete word
Alt + f - Move forward
Alt + l - Make word lowercase
Alt + n - Search the history forwards non-incremental
Alt + p - Search the history backwards non-incremental
Alt + r - Recall command
Alt + t - Move words around
Alt + u - Make word uppercase
Alt + back-space - Delete backward from cursor
Alt + Ctrl + e	 Expand command line.
Alt + Ctrl + ] x	 Where x is any character, moves the cursor backwards to the previous occurance of x.

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 dir
 
Esc-Del	 Delete previous word (may not work, instead try Esc followed by Backspace)
 
!! - run last command
!blah – run the most recent command that starts with ‘blah’ (e.g. !ls)
!blah:p – print out the command that !blah would run (also adds it as the latest command in the command history)
!$ – the last word of the previous command (same as Alt + .)
!$:p – print out the word that !$ would substitute
!* – the previous command except for the last word (e.g. if you typefind some_file.txt /‘, then !* would give you ‘find some_file.txt‘)
!*:p – print out what !* would substitute
!n	 Execute nth command in history
!^	 First argument of last command
^abc^xyz	 Replace first occurance of abc with xyz in last command and execute it

Indirect Referance

This is what i come across while writing some simple bash script.
But it seems really usefull. so i am just adding here.

| Example
for inst in instance{1..10}
do
	eval var1=\$$inst  ## to evaluate $inst in assignment you have to use \$$inst
	arry=($var1)
done

Source

If File Comparision

[ -a FILE ]	True if FILE exists.
[ -b FILE ]	True if FILE exists and is a block-special file.
[ -c FILE ]	True if FILE exists and is a character-special file.
[ -d FILE ]	True if FILE exists and is a directory.
[ -e FILE ]	True if FILE exists.
[ -f FILE ]	True if FILE exists and is a regular file.
[ -g FILE ]	True if FILE exists and its SGID bit is set.
[ -h FILE ]	True if FILE exists and is a symbolic link.
[ -k FILE ]	True if FILE exists and its sticky bit is set.
[ -p FILE ]	True if FILE exists and is a named pipe (FIFO).
[ -r FILE ]	True if FILE exists and is readable.
[ -s FILE ]	True if FILE exists and has a size greater than zero.
[ -t FD ]	True if file descriptor FD is open and refers to a terminal.
[ -u FILE ]	True if FILE exists and its SUID (set user ID) bit is set.
[ -w FILE ]	True if FILE exists and is writable.
[ -x FILE ]	True if FILE exists and is executable.
[ -O FILE ]	True if FILE exists and is owned by the effective user ID.
[ -G FILE ]	True if FILE exists and is owned by the effective group ID.
[ -L FILE ]	True if FILE exists and is a symbolic link.
[ -N FILE ]	True if FILE exists and has been modified since it was last read.
[ -S FILE ]	True if FILE exists and is a socket.
[ FILE1 -nt FILE2 ]	True if FILE1 has been changed more recently than FILE2, or if FILE1 exists and FILE2 does not.
[ FILE1 -ot FILE2 ]	True if FILE1 is older than FILE2, or is FILE2 exists and FILE1 does not.
[ FILE1 -ef FILE2 ]	True if FILE1 and FILE2 refer to the same device and inode numbers.
[ -o OPTIONNAME ]	True if shell option "OPTIONNAME" is enabled.
[ -z STRING ]	True if the length of "STRING" is zero.
[ -n STRING ] or [ STRING ]	True if the length of "STRING" is non-zero.
[ STRING1 == STRING2 ]	True if the strings are equal. "=" may be used instead of "==" for strict POSIX compliance.
[ STRING1 != STRING2 ]	True if the strings are not equal.
[ STRING1 < STRING2 ]	True if "STRING1" sorts before "STRING2" lexicographically in the current locale.
[ STRING1 > STRING2 ]	True if "STRING1" sorts after "STRING2" lexicographically in the current locale.
[ ARG1 OP ARG2 ]	"OP" is one of -eq, -ne, -lt, -le, -gt or -ge. These arithmetic binary operators return true if "ARG1" is equal to, 
                        not equal to, less than, less than or equal to, greater than, 
                        or greater than or equal to "ARG2", respectively. "ARG1" and "ARG2" are integers.

I/O Redirection

   1    COMMAND_OUTPUT >
   2       # Redirect stdout to a file.
   3       # Creates the file if not present, otherwise overwrites it.
   4 
   5       ls -lR > dir-tree.list
   6       # Creates a file containing a listing of the directory tree.
   7 
   8    : > filename
   9       # The > truncates file "filename" to zero length.
  10       # If file not present, creates zero-length file (same effect as 'touch').
  11       # The : serves as a dummy placeholder, producing no output.
  12 
  13    > filename    
  14       # The > truncates file "filename" to zero length.
  15       # If file not present, creates zero-length file (same effect as 'touch').
  16       # (Same result as ": >", above, but this does not work with some shells.)
  17 
  18    COMMAND_OUTPUT >>
  19       # Redirect stdout to a file.
  20       # Creates the file if not present, otherwise appends to it.
  21 
  22 
  23       # Single-line redirection commands (affect only the line they are on):
  24       # --------------------------------------------------------------------
  25 
  26    1>filename
  27       # Redirect stdout to file "filename".
  28    1>>filename
  29       # Redirect and append stdout to file "filename".
  30    2>filename
  31       # Redirect stderr to file "filename".
  32    2>>filename
  33       # Redirect and append stderr to file "filename".
  34    &>filename
  35       # Redirect both stdout and stderr to file "filename".
  36 
  37       #==============================================================================
  38       # Redirecting stdout, one line at a time.
  39       LOGFILE=script.log
  40 
  41       echo "This statement is sent to the log file, \"$LOGFILE\"." 1>$LOGFILE
  42       echo "This statement is appended to \"$LOGFILE\"." 1>>$LOGFILE
  43       echo "This statement is also appended to \"$LOGFILE\"." 1>>$LOGFILE
  44       echo "This statement is echoed to stdout, and will not appear in \"$LOGFILE\"."
  45       # These redirection commands automatically "reset" after each line.
  46 
  47 
  48 
  49       # Redirecting stderr, one line at a time.
  50       ERRORFILE=script.errors
  51 
  52       bad_command1 2>$ERRORFILE       #  Error message sent to $ERRORFILE.
  53       bad_command2 2>>$ERRORFILE      #  Error message appended to $ERRORFILE.
  54       bad_command3                    #  Error message echoed to stderr,
  55                                       #+ and does not appear in $ERRORFILE.
  56       # These redirection commands also automatically "reset" after each line.
  57       #==============================================================================
  58 
  59 
  60 
  61    2>&1
  62       # Redirects stderr to stdout.
  63       # Error messages get sent to same place as standard output.
  64 
  65    i>&j
  66       # Redirects file descriptor i to j.
  67       # All output of file pointed to by i gets sent to file pointed to by j.
  68 
  69    >&j
  70       # Redirects, by default, file descriptor 1 (stdout) to j.
  71       # All stdout gets sent to file pointed to by j.
  72 
  73    0< FILENAME
  74     < FILENAME
  75       # Accept input from a file.
  76       # Companion command to ">", and often used in combination with it.
  77       #
  78       # grep search-word <filename
  79 
  80 
  81    [j]<>filename
  82       # Open file "filename" for reading and writing, and assign file descriptor "j" to it.
  83       # If "filename" does not exist, create it.
  84       # If file descriptor "j" is not specified, default to fd 0, stdin.
  85       #
  86       # An application of this is writing at a specified place in a file. 
  87       echo 1234567890 > File    # Write string to "File".
  88       exec 3<> File             # Open "File" and assign fd 3 to it.
  89       read -n 4 <&3             # Read only 4 characters.
  90       echo -n . >&3             # Write a decimal point there.
  91       exec 3>&-                 # Close fd 3.
  92       cat File                  # ==> 1234.67890
  93       # Random access, by golly.
  94 
  95 
  96 
  97    |
  98       # Pipe.
  99       # General purpose process and command chaining tool.
 100       # Similar to ">", but more general in effect.
 101       # Useful for chaining commands, scripts, files, and programs together.
 102       cat *.txt | sort | uniq > result-file
 103       # Sorts the output of all the .txt files and deletes duplicate lines,
 104       # finally saves results to "result-file".

Ref : Faqs

Bash IRC Log

f(){ local first=$1 second=$2; shift; shift; echo "now, first arg is: $1, second arg is: $2, ... previously, \$1 
                    was: $first and \$2 was: $second"; }; f foo bar baz qux     
{ local -l reply; read -p "$1 [Y/n] " reply; [[ -z $reply || $reply = y?(es) ]]; }
cd src && find . -depth -type f -exec rm -f /path1/{} \; -o -type d -exec rmdir /path1/{} \;
gobackto() { local p="$PWD"; while [[ $p ]]; do if [[ ${p##*/} = "$1" ]]; then cd "$p"; return; fi; p=${p%/*}; done; return 1; }

Convert String to Array

It's simple and easy to convert string to array

$var1="testing is simple"
arry=($var1)
echo ${arry[1]}

Bash alias and complition

Using command completion for alias in bash.

~/.bash_profile
alias c='/usr/bin/ssh'
export HLIST
HLIST=`cat ~/.ssh/known_hosts | cut -f 1 -d ' ' | sed -e s/,.*//g | uniq | grep -v "\["`
HLIST="${HLIST} $(cat ~/.ssh/config | grep Host | awk '{print $2}' | grep -v \*)"
HLIST=$(echo ${HLIST} | sort | uniq)
complete -W "${HLIST}" c

Control case

In Bash 4:

To lowercase

$ string="A FEW WORDS"
$ echo ${string,}
a FEW WORDS
$ echo ${string,,}
a few words
$ echo ${string,,[AEIUO]}
a FeW WoRDS
 
$ string="A Few Words"
$ declare -l string
$ string=$string; echo $string
a few words

To uppercase

$ string="a few words"
$ echo ${string^}
A few words
$ echo ${string^^}
A FEW WORDS
$ echo ${string^^[aeiou]}
A fEw wOrds
 
$ string="A Few Words"
$ declare -u string
$ string=$string; echo $string
A FEW WORDS

Toggle (undocumented)

$ string="A Few Words"
$ echo ${string~~}
a fEW wORDS
$ string="A FEW WORDS"
$ echo ${string~}
a fEW wORDS
$ string="a few words"
$ echo ${string~}
A Few Words

Capitalize (undocumented)

$ string="a few words"
$ declare -c string
$ string=$string
$ echo $string
A few words

Title case:

$ string="a few words"
$ string=($string)
$ string=${string[@]^}
$ echo $string
A Few Words
 
$ declare -c string
$ string=(a few words)
$ echo ${string[@]}
A Few Words

To turn off a declare attribute, use “+”. For example, declare +c string. This affects subsequent assignments and not the current value.

Bash Tips / Tricks

Quating

Bash has a special form of quoting, $'string' in which backslash-character combinations are expanded. For example, echo $'this is a literal tab: \t'

re='foo.*bar'; [[ $'foo\nbar' =~ $re ]] && echo 'yes' || echo 'no'

History Size

HISTSIZE=1500000
HISTFILESIZE=1500000
HISTTIMEFORMAT="[%Y-%m-%d - %H:%M:%S] - "

Truth Table

These two commands not the same:
 
command1 && command2 || command3
 
if command1
then
command2
else
command3
fi

In the if-then-else, exactly one of command2 or command3 will be executed. But in the && || version, command3 runs if either command1 or command2 returns false.

for c1 in true false; do for c2 in true false; do echo "$c1 && $c2 || c3"; (echo c1; $c1) && (echo c2; $c2) || echo c3; done; done

And the output:

true && true || c3
c1
c2
true && false || c3
c1
c2
c3
false && true || c3
c1
c3
false && false || c3
c1
c3

Link to Article

Networked Info

Bash FAQ

bash.txt · Last modified: 2020/08/10 02:35 (external edit)