Skip to content

Instantly share code, notes, and snippets.

@HiroNakamura
Last active October 9, 2022 22:07
Show Gist options
  • Save HiroNakamura/5f728befc222c1da081958860bea36c9 to your computer and use it in GitHub Desktop.
Save HiroNakamura/5f728befc222c1da081958860bea36c9 to your computer and use it in GitHub Desktop.
Topics of my Linux, Bash, Git, Jenkins, Virtualisation and Docker

Programación en Bash Shell

Bash Shell

Básicamente es un lenguaje de scripting para realizar ciertas operaciones en entornos Linux.

holamundo.sh

#!/bin/bash

printf "\t [Programando en Bash Shell]"
echo $'\t'"Hola, mundo" 
Use case:
http://gitlab.com/UnderGrounder96/awx_install.git
Reference Bash:
https://tutorialkart.com/bash-shell-scripting/bash-tutorial/
shebang: #!/bin/bash
1 - Variables
SYSTEM VARIABLES vs USER VARIABLES
env command
$PWD, $USER, $HOME, $PS1
.env - https://github.com/UnderGrounder96/RentAcar/blob/master/.env.default
echo -e "$USER\n FooBar" # -e escapes newline
USER_VAR="HELLO" # defines USER_VAR as "hello"
USER_COM_VAR=`echo 'x'` # defines USER_VAR as "x", from command echo
USER_COM_VAR=$(echo 'x') # same as above
# this is a comment
echo $1, $2... ${10}
echo $@ # print args arr
echo $? # last result
echo $# # length
count=10 # -le, -lt, -eq, -ge, -gt
if [ $count -le 4 ]; then
echo "$count is less or equal to 4"
elif [[ $count -gt 4 && $count -lt 10 ]]; then # &&, ||
echo "$count is bewteen 5 and 10"
else
echo "$count has to be >=10"
fi
# if condition is false
if [ "hello" == "bye" ]; then # !=
echo "hello equals bye"
fi
if [ -f /file/path ]; then
echo "/file/path is a file"
fi
if [ -d /dir/path ]; then
echo "/dir/path is a dir"
fi
if [ -z “$hello” ]; then
echo "$hello is not empty"
fi
if [ $count -le 4 ]; then
echo "count is less or equal to 4 : $count"
elif [ $count -ge 5 ] && [ $count -lt 9 ]; then # (( $count >= 5 && $count <= 9 ))
echo "count is between to 5 and 9 : $count"
else
echo "count is greater than 9 : $count"
fi
case $variable in
A)
echo "A selected"
;;
B)
echo "B selected"
;;
C)
echo "C selected"
;;
*)
echo "ERROR! Please select between 1..3"
esac
#loops
while true; do
echo "hello" && break
done
a=1
b=2
count=10
while [[ $a -lt $count && $b -lt 5 ]]; do
a=$(( a + 1 ))
b=$(( b + 1 ))
done
# for (( i=0; i<5; i++ ))
for i in {0..5..2}; do #start..end..increment
echo "$i"
done
function main(){
# more code here
:
}
Reference Docker:
https://docs.docker.com/
https://www.tutorialspoint.com/docker/index.htm
Docker ps # shows running containers
Docker ps -a # shows all containers
Docker pull # pulls image from dockerhub.com
docker run hello-world # executes (and pulls) image hello-world
Docker start [container] # starts (up) the container
Docker stop [container] # stops running container
Docker logs [container] # showcases logs of container
Docker exec -it container_name bash # enters inside the container to perform bash commands
Docker rm container # removes (stopped) container
Docker rmi image # removes image
#!/bin/bash
# Comentarios multilínea
<< 'MULTILINE-COMMENT'
FUNDAMENTOS DE PROGRAMACION EN BASH SHELL
MULTILINE-COMMENT
# Limpiamos terminal
clear
echo $'\t'"[ Programando en Bash Shell]"
echo $'\t'"Hola, ${USER}"
echo $'\t'"Estamos en: ${PWD}"
echo -n "Esto sin nueva línea"
echo -e "\nRemoviendo \t backslash \t caracteres\n"
# 9.
numero=0
let aleatorio=$(expr 1 + $RANDOM % 10)
printf "\t [ Adivina un numero ]"
echo $'\n'"Introduce un numero:"
read numero
echo "$numero es el numero que introduciste"
echo "$aleatorio es el numero a adivinar"
if [ $numero -eq $aleatorio ]; then echo "Correcto"; else echo "Incorrecto"; fi
# 8. Bucle For
<< 'MULTILINE-COMMENT'
for (( contador=10; contador>0; contador-- ))
do
echo -n "$contador "
done
printf "\n"
for((contador=0; contador<5; contador++))
do
echo "contador: $contador"
done
printf "\n"
MULTILINE-COMMENT
# 7. Bucle while
<< 'MULTILINE-COMMENT'
valido=true
contador=1
echo $'\t'"Bucle While:"
while [ $valido ]
do
echo $contador
if [ $contador -eq 5 ];
then
break
fi
((contador++))
done
printf "\t Hecho !!\n"
echo "contador: $contador"
while [ $valido ]
do
echo $contador
if [ $contador -eq 0 ];
then
break
fi
((contador--))
done
printf "\t Hecho !!\n"
MULTILINE-COMMENT
# 6. Expresiones
<< 'MULTILINE-COMMENT'
((suma=65+22))
((resta=$suma-22))
((mult=$suma*$resta))
# Imprimir el resultado
echo "Suma: "$suma
echo "Resta: "$resta
echo "Multiplicacion: "$mult
MULTILINE-COMMENT
# 5. Definimos variables tipo Caracter, Entero, Booleano y del sistema
<< 'MULTILINE-COMMENT'
nombre="Codemonkey Junior"
entero=34
booleano=true
flotante=9.83
fecha=`date`
directorio=`pwd`
# Mostramos en pantalla el valor de las variables
printf "\t [Variables en Linux] "
echo "Hola, ${nombre}"
echo "Entero = ${entero}"
echo "Flotante = ${flotante}"
echo "Fecha: ${fecha}"
echo "Estamos en: ${directorio}"
MULTILINE-COMMENT
# 4. Comprobamos si una variable es NULL
<< 'MULTILINE-COMMENT'
if $booleano; then echo "Es verdadero: ${booleano}"; else echo "Es falso: ${booleano}"; fi
echo "Fecha de hoy es: ${fecha}"
echo "Estamos en el directorio: ${directorio}"
echo "El nombre del archivo es: $0"
MULTILINE-COMMENT
# 3. Realizamos algunas operaciones aritméticas
<< 'MULTILINE-COMMENT'
let num1=21
let num2=1
let suma=${num1}+${num2}
echo "num1=${num1}, num2=${num2}"
echo "Suma = ${suma}"
# Definimos las variables y su valor
let a=20
let b=5
# Operaciones aritméticas
let suma=$(expr ${a} + ${b})
let resta=$(expr ${a} - ${b})
let producto=`expr $a \* $b`
let division=$(expr ${a} / ${b})
echo "[Operaciones aritmeticas]"
echo "a = ${a}, b = ${b}"
echo "Suma = ${suma}"
echo "Resta = ${resta}"
echo "Producto = ${producto}"
echo "Division = ${division}"
let c=220
let d=200
let residuo=$(expr ${c} % ${d})
echo "c = ${c}, d = ${d}"
echo "Residuo = ${residuo}"
MULTILINE-COMMENT
# 2. Longitud de las variables
<< 'MULTILINE-COMMENT'
nombre='ABC'
echo "Cadena = ${nombre}"
# La longitud debe ser de 3
echo La longitud de la variable es: ${#nombre}
numero=4953
echo "Numero = ${numero}"
# La longitud debe ser de 4
echo La longitud de la variable es: ${#numero}
booleano=true
echo "Booleano = ${booleano}"
# En este la longitud será de 4, se cuenta cada una de las letras como si fuera un string
echo La longitud de la variable es: ${#booleano}
MULTILINE-COMMENT
# 1. Algunos comandos y variables de Linux
<< 'MULTILINE-COMMENT'
quien=`whoami`
donde=`pwd`
mishell=$SHELL
echo "Quien soy?: ${quien}"
echo "Donde estoy?: ${donde}"
echo "El home es: ${HOME}"
echo "El usuario es: ${USER}"
echo "El shell esta en: ${mishell}"
MULTILINE-COMMENT
Reference Git:
https://www.tutorialspoint.com/git/index.htm
curl -L https://raw.github.com/git/git/master/contrib/completion/git-prompt.sh > ~/.bash_git
ssh-keygen && cat ~/.ssh/*.pub # generate SSH key and prints public key
git config --list
git config --global user.name "Lucio Afonso"
git config --global user.email "[email protected]"
git config --global core.eol lf
git config --global color.ui "true"
git config --global core.editor "vim"
git config --global core.autocrlf input
git config --global credential.helper "store"
git clone https://github.com/git/git # clones git
git checkout -b LA/branch_name # creates and switches to branch LA/branch_name
git pull origin master # fetches and merges current branch with master
git add -A # stages (adds) files to git
git commit -m "F" # commits with the message "F"
git init # Initializing a repository
#Branching
git branch # shows local branches
git branch -a # shows local and remote branches
git branch -D la/extras # deletes branch la/extras
# Switching branches
git checkout branch_name # switches to branch_name
# Showcases status
git status
# Staging files
git add file1.js # Stages a single file
git add file1.js file2.js # Stages multiple files
git add -A # all files, new and modified
git add -u # all modified and staged files, not new files
# Committing the staged files
git commit -m "Message" # Commits with a one-line message
git commit # Opens the default editor to type a long message
# Adds remote origin as http://link/to/repo
git remote add origin http://link/to/repo
# Pushes branch to origin
git push origin branch
git push -d origin LA/branch_name # deletes LA/branch_name from origin
# Fetch vs pull
git fetch # updates all branches
git pull # same as above but merges
# Removes changes
git checkout -- file
git restore file
# Viewing the history
git log # Full history
git log -n 4 # Showcases last 4 from history
git stash # stashes all current changes
git reset --hard origin/master # resets HARD with master (aka sync)
git stash pop # applies last stashed changes
Reference Unix:
https://tutorialspoint.com/unix/index.htm
1 - Introduction:
Win - versions, File structure
Unix, AppleOS, Linux dist (Debian, Ubuntu, RedHat)
2 - Linux file structure
#1: Everything is a file
/bin, /boot...
/editable_text_config - extra configuration for commands
/media - auto mounted devices
/mnt - manual mounted devices
/opt - optional software, Dropbox is installed here.
/run - tmp folder used during boot
/var - variables files, /var/log is where log files are stored
3 - Full path vs relative path
/; ~ ; .. ; . # root filesystem
# hidden folder and files
.env/ # hidden folder
~/.bashrc # relative path of .bashrc
4 - Commands
# Intro: command [-flags] [args]
whoami, man vs --help, which, uname -a, yes
5 - File/Dir commands
pwd, cd, ls -lh, mkdir -p, rmdir -p
touch, cat, head -n 6, tail -n 3, more, less,
vi/nano, grep -nir, find / -name, cp, mv
clear, ctrl + L
rm -rvf dir
6 - Wildcards and Regular expression - *
Sdhasd\ dssd = "Sdhasd dssd" # they are equal
"Ds / ?sad"
rm -vf dir/* # erases everything from dir/
find . -name "*.txt"
7 - Multiple commands: Piping, and or grep
mkdir -p myFolder/dir && mv myFolder/ /tmp/
cd /tmp/myFolder/dir; hjkkjg; echo "No problem"
cat file.txt | grep tellus | less
8 - Redirects
cat /dev/null > file.txt # eliminates the content of a file
echo "Hasdad asd ad a" >> file.txt # appends what's in echo inside the file
find / -name dev_tools_default.img 2>/dev/null # hides errors
cat > /tmp/myFile.txt # type then ctrl+d, creates file
cat < /tmp/myFile.txt > /tmp/myFile2.txt # copies file
sdadas >file.log 2>&1 # redirects STDERR to STDOUT
bash script.sh 1>file.log 2>file.err # runs script.sh and creates 2 files, one for log and other for err
8- sudo/ su -/ sudo -i
chmod
systemctl
shutdown
reboot
apt install
9 - ping google.com -c 4 # pings 4 times
Reference Jenkins:
https://www.tutorialspoint.com/jenkins/index.htm
Reference Virtualisation:
https://www.tutorialspoint.com/virtualization2.0/index.htm
Reference Vagrant:
https://www.vagrantup.com/docs
Vagrant up
Vagrant ssh
Vagrant halt
Vagrant destroy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment