Bash

Bon, fallait que je m'y mette, voici un petit mémo bash :-)

Code snippets

Source: http://stackoverflow.com/questions/2500436/how-does-cat-eof-work-in-bash

# Assign multi-line string to a shell variable
sql=$(cat <<EOF
SELECT foo, bar FROM db
WHERE foo='baz'
EOF
)

# Pass multi-line string to a file in Bash
cat <<EOF > print.sh
#!/bin/bash
echo \$PWD
echo $PWD
EOF

# Pass multi-line string to a pipe in Bash
cat <<EOF | grep 'b' | tee b.txt
foo
bar
baz
EOF

# To remove leading tabs (usefull for nice indenting)
cat <<-EOF
<tab>a
<tab>EOF

# To define a multi line variable
read -r -d '' VARIABLE << EOM
This is line 1.
This is line 2.
Line 3.
EOM

# Same but with indentation (code style only):
read -r -d '' VARIABLE <<- EOM
    This is line 1.
    This is line 2.
    Line 3.
EOM

# C'est aussi possible avec echo et bash
echo -e "this" "is" "line" "one\n" "this" "is" "line" "two\n"  ...
printf "%s\n" "this is line one" "this is line two" "this is line three" > filename
printf "%s\n" "this is line "{one,two,three} > filename

source: http://stackoverflow.com/questions/10929453/read-a-file-line-by-line-assigning-the-value-to-a-variable

# Premiere forme
filename="$1"
while read -r line
do
    name="$line"
    echo "Name read from file - $name"
done < "$filename"

# deuxieme forme
cat filename | while read LINE
do
echo $LINE
done

Redirections: Sources: http://stackoverflow.com/questions/637827/redirect-stderr-and-stdout-in-a-bash-script,

# Pour piper une variable sans utiliser echo
sed 's/toto/tata/'<<<"$ligne"
awk '{print $0}' <<< "$variable"

# stdout 2 stderr
grep da * 1>&2 

# stderr 2 stdout
grep * 2>&1

# stderr and stdout 2 file
rm -f $(find / -name core) &> /dev/null 
yourcommand 1>> filename 2>&1 # But &>> work on bash4


# stderr and stdout 2 stdout and file
grep -Ri toto  2>&1 | tee -a some_file

#  stderr to stdout and the stdout into a file
grep -Ri toto > some_file  2>&1 

# stdout plus stderr written into a log file and stderr still on console
command 3>&1 1>&2 2>&3 1>>logfile | tee -a logfile

# To apply to the whole file, checkout: http://stackoverflow.com/a/20564208

Arguments management

Avec des positional arguments

numargs=$#

for ((i=1 ; i <= numargs ; i++)) ; do

    # Shift to next argument
    argument="${1}"
    shift 1

    # Anaylyse arguments
    case "${argument}" in
        list )
            cat ${sfl_doc_db}
            ;;
        update )
            update_db
            fix_perms
            ;;
        create )
            doc_create $@
            ;;
        help )
            show_help
            ;;

# Not implemented yet ...
        show )
            echo show_doc $@
            ;;
        search )
            echo search_keyword $@
            ;;
        * )
            echo "ERROR: Unknown argument: ${argument}"
            show_help
            ;;
    esac


done

Avec getops

#!/bin/sh

# Usage info
show_help() {
cat << EOF
Usage: ${0##*/} [-hv] [-f OUTFILE] [FILE]...
Do stuff with FILE and write the result to standard output. With no FILE
or when FILE is -, read standard input.

    -h          display this help and exit
    -f OUTFILE  write the result to OUTFILE instead of standard output.
    -v          verbose mode. Can be used multiple times for increased
                verbosity.
EOF
}

# Initialize our own variables:
output_file=""
verbose=0

OPTIND=1
# Resetting OPTIND is necessary if getopts was used previously in the script.
# It is a good idea to make OPTIND local if you process options in a function.

while getopts hvf: opt; do
    case $opt in
        h)
            show_help
            exit 0
            ;;
        v)  verbose=$((verbose+1))
            ;;
        f)  output_file=$OPTARG
            ;;
        *)
            show_help >&2
            exit 1
            ;;
    esac
done
shift "$((OPTIND-1))" # Shift off the options and optional --.

# Everything that's left in "$@" is a non-option.  In our case, a FILE to process.
printf 'verbose=<%d>\noutput_file=<%s>\nLeftovers:\n' "$verbose" "$output_file"
printf '<%s>\n' "$@"

# End of file

Source: http://mywiki.wooledge.org/BashFAQ/035

Tests

# Test regex:
if [[ $gg =~ ^....grid.*$ ]] ; then echo $gg; fi

Forcer la casse:
echo "$a" | tr '[:upper:]' '[:lower:]'
echo "$a" | awk '{print tolower($0)}'

# Bash 3/4
echo "${a,,}"
echo "${string,,[AEIUO]}"
echo "${string^^}"

Conditions et blocks

Tester si une variable est vide ou remplie:
VAR="hello"
if [ -n "$VAR" ]; then
    echo "VAR is not empty"
fi

VAR=""
if [ -z "$VAR" ]; then
    echo "VAR is empty"
fi
La structure if:
if [ test ]; then
	echo "Le premier test a été vérifié"
elif [ autre_test ]; then
	echo "Le second test a été vérifié"
elif [ encore_autre_test ]; then
	echo "Le troisième test a été vérifié"
else
	echo "Aucun des tests précédents n'a été vérifié"
fi
Le for:
for i in $( ls ); do
	echo item: $i
done
Le while:
COUNTER=0
while [  $COUNTER -lt 10 ]; do
	echo The counter is $COUNTER
	let COUNTER=COUNTER+1 
done
Le untill:
COUNTER=20
until [  $COUNTER -lt 10 ]; do
	echo COUNTER $COUNTER
	let COUNTER-=1
done
La structure case:
# Case
case $space in
	[1-6]*)
		Message="All is quiet."
		;;
	[7-8]*)
		Message="Start thinking about cleaning out some stuff.  There's a partition that is $space % full."
		;;
	9[1-8])
		Message="Better hurry with that new disk...  One partition is $space % full."
		;;
	99)
		Message="I'm drowning here!  There's a partition at $space %!"
		;;
	*)
		Message="I seem to be running with an nonexistent amount of disk space..."
		;;
esac

Variables

Incrémenter une variable:
var=$((var+1))

Les commandes utiles

Commandes pour récupérer des bouts de fichier:
# Récupérer la premiere lignes
head -n 1

# Récupérer tout sauf la première ligne
sed '1 d'

# Récupérer la dernière lignes
tail -n 1

# Récupérer tout sauf la dernière ligne
head -n -1
Creer des fichiers uniques:
cur_date=$(date +%Y-%m-%d_%H-%M-%S)


AWK

Exemples:
echo "$variable" | awk '{print $0}'

# Pour passer une variable dans awk, sans echo
awk -v r=$root '{ print "shell root value - " r}'
awk -v var="$variable" 'BEGIN {print var}'

References

http://wiki.bash-hackers.org/syntax/pe

Keystrokes

Ctrl + A	Go to the beginning of the line you are currently typing on
Ctrl + E	Go to the end of the line you are currently typing on
Ctrl + L              	Clears the Screen, similar to the clear command
Ctrl + U	Clears the line before the cursor position. If you are at the end of the line, clears the entire line.
Ctrl + H	Same as backspace
Ctrl + R	Let’s you search through previously used commands
Ctrl + C	Kill whatever you are running
Ctrl + D	Exit the current shell
Ctrl + Z	Puts whatever you are running into a suspended background process. fg restores it.
Ctrl + W	Delete the word before the cursor
Ctrl + K	Clear the line after the cursor
Ctrl + T	Swap the last two characters before the cursor
Esc + T	Swap the last two words before the cursor
Alt + F	Move cursor forward one word on the current line
Alt + B	Move cursor backward one word on the current line
Tab	Auto-complete files and folder names
# Mouvement
^a: Déplace le curseur au début de ligne.
^e: Déplace le curseur en fin de ligne.
^f: Avance le curseur de un caractère.
^b: Recule le curseur de un caractère.
^l: Nettoie l’écran.

# Couper/Coller
^k: Efface le texte en avant du curseur.
^u: Efface le texte en arrière du curseur.
Alt+d: Efface le mot en avant du curseur.
^y: Insert le texte effacé.
^+retour  arrière: Efface  le  texte  du  mot  en  avant  du caratère.  Si  le  curseur  est  sur  la première   lettre,   efface   le   mot précédent.
Page last modified on April 07, 2017, at 05:26 AM EST