Bash
source
~% FILE="example.tar.gz"
~% echo "${FILE%%.*}"
example
~% echo "${FILE%.*}"
example.tar
~% echo "${FILE#*.}"
tar.gz
~% echo "${FILE##*.}"
gz
assign var from command output
var="$(echo "eat at joe's")"
uppercase var
echo "${var^^}"
lowercase var
echo "${var,,}"
slice var
"${VAR:offset:length}"
increment var
i=$((i+1))
native regex
if [[ "$var" =~ [0-9]{3} ]]
then
echo 'it matches'
fi
print line number
echo "$LINENO"
clear starship error code
true
check for program
if (! type 7z > /dev/null 2>&1 )
then
echo "7zip not installed"
fi
assign to an array
myArray=()
myArray+=("$var")
count array elements
echo "array has ${#myArray[@]} items"
count args
echo "$#"
iterate an array
for var in "${myArray[@]}"
do
echo "$var"
done
iterate args
for arg in "$@"
do
echo "$arg"
done
iterate lines
while read -r line
do
echo "$line"
done < <(echo "$lines")
substring
# ${string:offset:length}
var="hello world"
echo "${var:0:5} bob"
move to beginning and clear line
echo -ne "\r\033[2K task x% done"
date gate
if [[ "$(date '+%s')" -lt "$(date --date '2552-09-28' '+%s')" ]]
then
echo 'skippy skippy'
exit 0
fi
capture output and test success
if output=$(ls * 2>&1)
then
echo "success"
else
echo "failure"
fi
use variable in place of file
echo -n 'one\ntwo\nthree' | grep -f <(echo -e 'two\nthree\nfour')
test operators
| operator |
desc |
-eq |
equal to |
-gt |
greater than |
-ge |
greater than or equal to |
-lt |
less than |
-le |
less than or equal to |
-f |
file exists |
-d |
directory exists |
-e |
anything exists |
-x |
file is executable |
-ef |
file path equals |
-n |
string is not empty |
-z |
string is empty |
using operators
if [[ "$var" -gt 0 ]]
then
echo "yep it's greater than zero"
fi
if test "$var" -gt 0
then
echo "yep it's greater than zero"
fi
TODO
- add preferred arg parsing method