Last active
June 13, 2025 04:06
-
-
Save peeweek/863d8c17c823d44e5bbc4b411c1b76a9 to your computer and use it in GitHub Desktop.
Cheat sheet (bash script)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Comments are like that | |
# First line is the shebang with #, !, then path to the executable (meaning it can be /bin/python) | |
##################### | |
## STATEMENTS | |
##################### | |
# One Statement per line | |
foo="Bar" | |
echo $foo | |
# Chained Statements on same line | |
foo="Bar";echo $foo | |
##################### | |
## VARIABLES | |
##################### | |
# Variable assignment : using '=' (no spaces around) | |
some_variable="Some string Value" | |
other_variable=12 | |
variable_from_command_output=`uname -a` | |
# OR | |
variable_from_command_output=$(uname -a) | |
# Using variables by prefixing them with '$' | |
echo $variable_from_command_output | |
# concatenate | |
some_other=$some_variable$other_variable | |
# $some_other equals "Some string Value12" | |
# format string | |
format_other="Twelve is "$other_variable | |
format_other="Twelve is ${other_variable}" | |
# Built-in Variables | |
# $0 contains the call to the script, as it is typed | |
echo "Command line is '${0}'" | |
# $1 $2 $3 ... are the arguments of the script, beware, if they are not present they will be empty | |
echo "Arguments are '$1' '$2' '$3'" | |
# $# contains the number of arguments | |
echo "You passed $# arugment(s)" | |
#################################### | |
## READING FILES | |
#################################### | |
while read -r line; do | |
echo "$line" | |
done < filename.txt | |
#################################### | |
## STRING SEARCH/REPLACE | |
#################################### | |
searchString="I love Suzy and Mary" | |
search="Suzi" | |
replace="Sara" | |
echo "${searchString/"$search"/"$replace"}" | |
# prints 'I love Sara and Mary' | |
#To replace all occurrences, use ${parameter//pattern/string}: | |
message='The secret code is 12345' | |
echo "${message//[0-9]/X}" | |
# prints 'The secret code is XXXXX' | |
#################################### | |
## UTILITIES | |
#################################### | |
script_absolute_directory=$(dirname $(readlink -f $0)) | |
echo "Current Script absolute directory is $script_absolute_directory" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment