Bash Commands

Published: 2019-08-04, Updated: 2023-03-14

Ler variável de forma interativa

read -e -p "Enter Your Name:" -i "Ricardo" NAME

Testar coisas com test

test "$(echo hi | grep Olá)" = "Swarm: active"; echo $?
test $(echo 1) -eq $(echo 1)
echo $?
0

test $(echo 1) -eq $(echo 2)
echo $?
1

IF ELSE - Compare two strings

export DOWNLOAD_API_FROM_REMOTE=1
if [ "$DOWNLOAD_API_FROM_REMOTE" = "1" ]; then
	echo "1";
else
	echo "outro"; 
fi

Verificar se o arquivo existe

if [ ! -f /tmp/foo.txt ]; then
    echo "File not found!"
fi

file exists

if [ -a FILE ]; then
	echo "hi"
fi

verificar se a string está vazia

if [ -z "" ]; then
  echo "hi"
fi

Formatar um numero com leading zeros

I=1
NUMBER_FORMATTED=`printf '%03d' $I`

Ler arquivo posicional no bash

while read -d $'\n' i; do echo $i;done <./dates
while read -d $'\n' i; do . the_script $i;done <./dates

Ler do stdin

#!/bin/bash

while read i ; do
	echo "> Downloading: $i"
	wget "www.nesfiles.com$i"
done < "${1:-/dev/stdin}"

For de 1 em 1

for i in {1..10}; do echo $i; done

Exemplo de Function

function system_info {
	echo $1
}
system_info "mySystem"

Esse funciona tanto com shell como bash

hello(){
	echo "V=$REPO_TOKEN, 0=$0, 1=$1, 2=$2"
}

Funçao com parametros

sc.sh

#!/bin/sh
hello(){
	echo "V=$REPO_TOKEN, 0=$0, 1=$1, 2=$2"
}
hello a b

chamando

export REPO_TOKEN='37b366a8b7495ef2f0ca3f0d5e20bd095ce1b314' && source sc.sh

saida

V=37b366a8b7495ef2f0ca3f0d5e20bd095ce1b314, 0=/bin/bash, 1=a, 2=b

Setar variavel senao existir

c=${c:-default}

Somar dois numeros

echo 2 3 | awk '{print $1 + $2}'

Fazer for no arquivo

for  i in $(cat /tmp/node_modules.log) ;  do echo $i; done

Tirar sufixo da variavel

VIRUS="trojan.exe" && echo ${VIRUS%.exe}
trojan

If composto com and

if [ "$(ls -A /tmp)" ] && [ -d /tmp ]; then
   echo "Not Empty"
else
	echo "Not Empty"$
fi

Loop through file lines

while read l; do
	echo $l ; 
done <apps.txt

Loop through command output

cat apps.txt |\
while read l ; do
	echo $l;
done

Switch case com bash

case "orange" in
	orange )
		echo "orange selected"
	;;
	grape )
		echo "grape selected"
	;;
esac

For nos arquivos do diretório

for f in *.jpg; do \
 echo "$f - "${i%.jpg}.wtf"
done

Checar se string contém conteudo

CURRENT_JAVA_VERSION=$(java -version 2>&1)
EXPECTED_JAVA_VERSION="17"
if echo "${CURRENT_JAVA_VERSION}" | grep -q "${EXPECTED_JAVA_VERSION}"; then
  echo "contains!"
fi

Rodar comando se ele existir

echo "$(java -version 2>&1)" | grep -q "17" && echo "JDK 17 instalada"

Validar retorno função

function runAndExit () {
  echo ${X}
  return 1
}

export X="valor de x"
echo "Antes"
runAndExit || echo "Deu erro"
echo "Depois"
$ bash tmp.sh 
Antes
valor de x
Deu erro
Depois

Bash group command

{ cmd1; cmd2; cmd3; }; sleep 1; { cmd4; cmd5;}

Usando test command

$ test 1 -eq 1

$ test 1 -eq 1 ; echo $?
0

$ test 1 -eq 1 -a 2 -eq 2  ; echo $?
0

$ test 1 -eq 1 -a 2 -eq 3  ; echo $?
1

$ test 1 -eq 1 -a 2 -eq 3  ; echo $?
1

$ test 1 -eq 1 -o 2 -eq 3  ; echo $?
0

Sair com codigo zero quando erro esperado, sair com erro quando erro inesperado e continuar quando sem erro

( 
{ ( exit 4 ); EXITCODE=$?; } \
&& test $EXITCODE -eq 3 && echo "expected error" && exit 0 \
|| test $EXITCODE -ne 0 && echo "unkown error" && exit $EXITCODE \
|| echo "code zero: ${EXITCODE}"
)

$ exit 3
expected error

$ exit 0
code zero: 0

$ exit 4
unkown error

Validar se tag do git existe ou não

Via exit code

$ git rev-parse "3.9.2xx^{}" >/dev/null 2>&1; echo $?

$ git rev-parse "${APP_VERSION}^{}" >/dev/null 2>&1 && echo "> Already released" && exit 3 || echo "Not released yet"

Usando if


if git rev-parse "$APP_VERSION^{}" >/dev/null 2>&1; then
  echo "> Tag already exists $APP_VERSION"
  exit 3
fi

bash commands, bash bookmarks, shell bookmarks, shell commands


Sublime Atalhos IO Redirection in Bash

Comments