Skip to content

Shell

Terminal window
set -euo pipefail
IFS=$'\n\t'

See: Unofficial bash strict mode

Modifier les couleurs dans un shell (RedHat)

Section titled “Modifier les couleurs dans un shell (RedHat)”

Editer le fichier /etc/DIR_COLORS et remplacer DIR 00;34 # directory par DIR 00;32 # directory

Terminal window
echo -en "\ec"
Terminal window
echo $((0+0))
Terminal window
$((a + 200)) # Add 200 to $a
Terminal window
$(($RANDOM%200)) # Random number 0..199
Terminal window
echo -n "Proceed? [y/n]: "
read ans
echo $ans
Terminal window
while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
-V | --version )
echo $version
exit
;;
-s | --string )
shift; string=$1
;;
-f | --flag )
flag=1
;;
esac; shift; done
if [[ "$1" == '--' ]]; then shift; fi
Terminal window
python hello.py > output.txt # stdout to (file)
python hello.py >> output.txt # stdout to (file), append
python hello.py 2> error.log # stderr to (file)
python hello.py 2>&1 # stderr to stdout
python hello.py > output.txt 2>&1 # stderr to stdout (file and no screen output)
python hello.py 2>/dev/null # stderr to (null)
python hello.py &>/dev/null # stdout and stderr to (null)
ExpressionDescription
$HOMEchemin du répertoire personnel de l’utilisateur
$OLDPWDchemin du répertoire précédent
$PATHliste des chemins de recherche des commandes exécutables
$PPIDPID du processus père du shell
$PS1invite principale du shell
$PS2invite secondaire du shell
$PS3invite de la structure shell “select”
$PS4invite de l’option shell de débogage “xtrace”
$PWDchemin du répertoire courant
$RANDOMnombre entier aléatoire compris entre 0 et 32767
$REPLYvariable par défaut de la commande “read” et de la structure shell “select”
$SECONDSnombre de secondes écoulées depuis le lancement du shell
ExpressionDescription
$?Exit status de la dernière tache
$!PID de la dernière tache en BG
$$PID du shell
$0Nom du script shell
ExpressionDescription
$#Nombre d’arguments
$*Tous les arguments
$@Tous les arguments, en commencant par le premier
$1Premier argument
$_Argument de la dernière commande
ExpressionDescription
${FOO:-val}$FOO, or val if unset (or null)
${FOO:=val}Set $FOO to val if unset (or null)
${FOO:+val}val if $FOO is set (and not null)
${FOO:?message}Show error message and exit if $FOO is unset (or null)

Omitting the : removes the (non)nullity checks, e.g. ${FOO-val} expands to val if unset otherwise $FOO.

ExpressionDescription
${FOO:0:3}Substring (position, length)
${FOO:(-3):3}Substring from the right
ExpressionDescription
${#FOO}Taille de la variable $FOO
Terminal window
echo {A,B}.js
ExpressionDescription
{A,B}Same as A B
{A,B}.jsSame as A.js B.js
{1..5}Same as 1 2 3 4 5

variable

Terminal window
STR="HELLO WORLD!"
echo ${STR,} #=> "hELLO WORLD!" (lowercase 1st letter)
echo ${STR,,} #=> "hello world!" (all lowercase)
STR="hello world!"
echo ${STR^} #=> "Hello world!" (uppercase 1st letter)
echo ${STR^^} #=> "HELLO WORLD!" (all uppercase)
Terminal window
name="John"
echo ${name}
echo ${name/J/j} #=> "john" (substitution)
echo ${name:0:2} #=> "Jo" (slicing)
echo ${name::2} #=> "Jo" (slicing)
echo ${name::-1} #=> "Joh" (slicing)
echo ${name:(-1)} #=> "n" (slicing from right)
echo ${name:(-2):1} #=> "h" (slicing from right)
echo ${food:-Cake} #=> $food or "Cake"

répertoire

Terminal window
STR="/path/to/foo.cpp"
echo ${STR%.cpp} # /path/to/foo
echo ${STR%.cpp}.o # /path/to/foo.o
echo ${STR%/*} # /path/to
echo ${STR##*.} # cpp (extension)
echo ${STR##*/} # foo.cpp (basepath)
echo ${STR#*/} # path/to/foo.cpp
echo ${STR##*/} # foo.cpp
echo ${STR/foo/bar} # /path/to/bar.cpp
Terminal window
STR="Hello world"
echo ${STR:6:5} # "world"
echo ${STR: -5:5} # "world"
Terminal window
SRC="/path/to/foo.cpp"
BASE=${SRC##*/} #=> "foo.cpp" (basepath)
DIR=${SRC%$BASE} #=> "/path/to/" (dirpath)
CodeDescription
${FOO%suffix}Supprimer suffix
${FOO#prefix}Supprimer prefix
------
${FOO%%suffix}Supprimer long suffix
${FOO##prefix}Supprimer long prefix
------
${FOO/from/to}Remplacer premier match
${FOO//from/to}Remplacer tout
------
${FOO/%from/to}Remplacer suffix
${FOO/#from/to}Remplacer prefix
Terminal window
Fruits=('Apple' 'Banana' 'Orange')
Terminal window
Fruits[0]="Apple"
Fruits[1]="Banana"
Fruits[2]="Orange"
Terminal window
echo ${Fruits[0]} # Element #0
echo ${Fruits[-1]} # Last element
echo ${Fruits[@]} # All elements, space-separated
echo ${#Fruits[@]} # Number of elements
echo ${#Fruits} # String length of the 1st element
echo ${#Fruits[3]} # String length of the Nth element
echo ${Fruits[@]:3:2} # Range (from position 3, length 2)
echo ${!Fruits[@]} # Keys of all elements, space-separated
Terminal window
Fruits=("${Fruits[@]}" "Watermelon") # Push
Fruits+=('Watermelon') # Also Push
Fruits=( ${Fruits[@]/Ap*/} ) # Remove by regex match
unset Fruits[2] # Remove one item
Fruits=("${Fruits[@]}") # Duplicate
Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
lines=(`cat "logfile"`) # Read from file
#!/bin/bash
declare -A dict
dict=( [‘a’]=1
[‘b’]=2
[‘c’]=3 )
for item in ${!dict[@]}
do
echo $item => ${dict[$item]}
done

On déclare sound en tant que dictionnaire (couple clé:valeur)

Terminal window
declare -A sounds
Terminal window
sounds[dog]="bark"
sounds[cow]="moo"
sounds[bird]="tweet"
sounds[wolf]="howl"
Terminal window
echo ${sounds[dog]} # Dog's sound
echo ${sounds[@]} # All values
echo ${!sounds[@]} # All keys
echo ${#sounds[@]} # Number of elements
unset sounds[dog] # Delete dog
Terminal window
for val in "${sounds[@]}"; do
echo $val
done
Terminal window
for key in "${!sounds[@]}"; do
echo $key
done

Terminal window
for i in /etc/rc.*; do
echo $i
done
Terminal window
for ((i = 0 ; i < 100 ; i++)); do
echo $i
done
Terminal window
for i in {1..5}; do
echo "Welcome $i"
done
Terminal window
for i in {5..50..5}; do
echo "Welcome $i"
done
Terminal window
cat file.txt | while read line; do
echo $line
done
Terminal window
while true; do
···
done

Afficher un ou des process sans le process grep himself

Section titled “Afficher un ou des process sans le process grep himself”
Terminal window
ps - elf | grep squid | grep -v grep
ou
ps -elf | grep [s]quid

Affichier un fichier sans les commentaires

Section titled “Affichier un fichier sans les commentaires”
Terminal window
grep -E -v '^(#|$)' <fichier>
ou
egrep -v '^(#|$)' <fichier>
Terminal window
egrep -i "apache|lsyncd" <file>
ou
grep -i -e apache -e lsyncd <file>
Terminal window
if grep -q 'foo' ~/.bash_history; then
echo "You appear to have typed 'foo' in the past"
fi
Terminal window
ls toto 2>&1 | tee -a toto.log;
echo ${PIPESTATUS[0]} #RC Avant pipe
echo $? #RC après pipe
awk 'sub(/^M/, "");1' <ficsource> <ficmaj>
awk -F"\t" '{ print $56 }'
awk 'BEGIN{print 1024 / 1000}'

Selectioner la première ou la dernière ligne + imprimer un champ

Section titled “Selectioner la première ou la dernière ligne + imprimer un champ”
awk 'BEGIN{print $2}'
awk 'END{print $2}'
Terminal window
sed 's/^M//g' <ficsource> <ficmaj>
ou
sed -i 's/^M//g' <ficsource>
Terminal window
sed -e " //{N;s/Hxxxxx/Pxxxxx/g;} "\

Supprimer les caractères “Newline” (LF)

Section titled “Supprimer les caractères “Newline” (LF)”
Terminal window
sed -i '{:q;N;s/\n//g;t q}' days.txt

Supprimer les 10 premiers caractères de chaque ligne

Section titled “Supprimer les 10 premiers caractères de chaque ligne”
Terminal window
sed -i 's/^.\{10\}//g' fichier.txt
Terminal window
<code>sed -n 1p check_toto.txt
Terminal window
if [ -n "$(echo $var | sed 's/[0-9]//g')" ]; then
echo 'is not numeric'
else
echo 'is numeric'
fi
Terminal window
for i in "$@";
do
BN=$(basename "${i%.*}")
...
done
Terminal window
DIR="$(readlink -f "$(dirname "$0")/../data/transfers")"

Le script $(basename ${0}) est correctement exécuté

Renommer l’extension de plusieurs fichiers

Section titled “Renommer l’extension de plusieurs fichiers”
find . -name '*.mp4' | rename mp4 txt *
find / -xdev -type f -exec grep -i toto {} /dev/null \;
find . -type f -mtime +7 -name « *.trc » -exec rm -f {} \;
find . -type f -mtime +2 -size xx -exec rm {}; avec xx = 10M ou 10K par ex
find . -type f -mtime +2 -name /*/backup/*/ -exec rm {}; (enlever les / )
find . -type f -mtime +1 -exec rm

Recherche “mot-clé” avec redirection log

Section titled “Recherche “mot-clé” avec redirection log”
find . -type f -print | xargs grep -i « my_string_to_search »> /tmp/search.log 2>/dev/null;

Recherche des fichiers sans arborescence répertoire

Section titled “Recherche des fichiers sans arborescence répertoire”
find . -name '*.txt' -exec basename {} \;
Terminal window
git commit && git push
git commit || echo "Commit failed"
Terminal window
if [[ -z "$string" ]]; then
echo "String is empty"
elif [[ -n "$string" ]]; then
echo "String is not empty"
fi
ConditionDescription
[[ -z STRING ]]Empty string
[[ -n STRING ]]Not empty string
[[ STRING == STRING ]]Equal
[[ STRING != STRING ]]Not Equal
------
[[ NUM -eq NUM ]]Equal
[[ NUM -ne NUM ]]Not equal
[[ NUM -lt NUM ]]Less than
[[ NUM -le NUM ]]Less than or equal
[[ NUM -gt NUM ]]Greater than
[[ NUM -ge NUM ]]Greater than or equal
------
[[ STRING =~ STRING ]]Regexp
------
(( NUM < NUM ))Numeric conditions
ConditionDescription
[[ -o noclobber ]]If OPTIONNAME is enabled
------
[[ ! EXPR ]]Not
[[ X && Y ]]And
`[[ X
ConditionDescription
[[ -e FILE ]]Exists
[[ -r FILE ]]Readable
[[ -h FILE ]]Symlink
[[ -d FILE ]]Directory
[[ -w FILE ]]Writable
[[ -s FILE ]]Size is > 0 bytes
[[ -f FILE ]]File
[[ -x FILE ]]Executable
------
[[ FILE1 -nt FILE2 ]]1 is more recent than 2
[[ FILE1 -ot FILE2 ]]2 is more recent than 1
[[ FILE1 -ef FILE2 ]]Same files
Terminal window
# String
if [[ -z "$string" ]]; then
echo "String is empty"
elif [[ -n "$string" ]]; then
echo "String is not empty"
else
echo "This never happens"
fi
Terminal window
# Combinations
if [[ X && Y ]]; then
...
fi
Terminal window
# Equal
if [[ "$A" == "$B" ]]
Terminal window
# Regex
if [[ "A" =~ . ]]
Terminal window
if (( $a < $b )); then
echo "$a is smaller than $b"
fi
Terminal window
if [[ -e "file.txt" ]]; then
echo "file exists"
fi
Terminal window
log_and_die() {
>&2 echo "[FATAL] $*"
exit 1
}