.bashrc.extra
:D
Use =~
followed by a regular expression pattern. Do not enclose the pattern in quotes if using in a test
block.
Check if a variable is a positive integer:
[[ $1 =~ ^[0-9]+$ ]]
Functions are created and called the same as any shell script: use command line arguments as parameters to pass, and echo any output.
function parse_input() { INPUT=$1 echo "You passed ${1} as an argument" }
cat filename | while read line; do echo "Your line says ${line}" done
Syntax: ${variable:<starting integer>[:<num characters>]}
string="O hai" echo ${string:2} # returns hai
Get string length
${#string} expr length $string
Find the index of the first occurrence of a letter in a string
Returns 0 on not found.
expr index abcdefg d
Strings as commands
You need to use eval
to reparse a command through bash.
See here
#!/bin/bash cmd="date --date=\"1 days ago\"" $cmd # Doesn't work eval $cmd # Works
Simple sed replacement
echo testing testing2 | sed -e 's/ /\|/' # returns testing|testing2
Simple cut with a delimiter, grabbing a field
eix --only-names -Ie bash | cut -d "/" -f 2
When setting a variable using the backtick operator, use double quotes around the variable to retain newlines.
files=`ls` echo "$files"
Get the size of the available cols, lines. Useful when writing shell applications that display output that needs to be paged:
tput cols tput lines
“Wonder piping!” –Shaine
$ true | false | true $ echo ${PIPESTATUS[*]}
$#
Number of arguments on commandline.$?
Exit status of last command.$$
Process id of current program.$!
Process id of last backgroundjob or background function.$0
Program name including the path if started from another directory.$1..n
Commandline arguments, each at a time.$*
All commandline arguments in one string.Color | Normal | Bold |
---|---|---|
Gray | 00;38 | 01;30 |
Black | 00;30 | |
Red | 00;31 | 01;31 |
Green | 00;32 | 01;32 |
Purple 1 | 00;33 | 01;33 |
Blue | 00;34 | 01;34 |
Purple 2 | 00;35 | 01;35 |
Cyan | 00;36 | 01;36 |
White | 00;37 | 01;38 |
Bright Blue | 01;37 | |
Yellow | 02;33 | |
Dark Gray |
You can use trap
to capture a signal, such as Ctl-C to kill a command, and then map it to an internal function inside the bash script.
This is useful in scenarios where a shell script calls other scripts, and cancelling them would only cancel that one executed script instead of the main one.
control_c() { exit 1 } trap control_c INT
Check to see if input is an integer:
if [[ $1 == ?(-)+([0-9]) ]]; then echo "$1 is an integer"; fi