Bash Commands

Published: 2019-08-04, Updated: 2022-07-16

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

bash commands, bash bookmarks, shell bookmarks, shell commands


Sublime Atalhos IO Redirection in Bash

Comments