Bash

Wiki.Bash History

Hide minor edits - Show changes to output

Added lines 39-44:

# Pour lire un csv
while IFS=',' read -r f1 f2 f3 f4 f5 f6 f7
do
  echo "$f1 $f2 $f3 $f4 $f5 $f6 $f7"
done < "/path/to/your/input/file.cvs"
Added lines 149-199:

[@
#!/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
Added lines 33-51:
# 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

Added lines 101-148:

!! 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
Changed lines 58-59 from:
to:
awk '{print $0}' <<< "$variable"
Changed lines 91-92 from:

!! Conditions
to:
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
Changed lines 114-125 from:
if [ conditional expression1 ]
then
statement1
statement2
.
elif [ conditional expression2
]
then
statement3
statement4
.
.
.
to:
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é"
Changed line 121 from:
statement5
to:
echo "Aucun des tests précédents n'a été vérifié"
Changed lines 125-127 from:
!! Variables
Incrémenter une variable:
[@
var=$((var+1))
to:
Le for: [@
for i in $( ls ); do
echo item: $i
done
Changed lines 131-148 from:
!! 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)

to:
Le while: [@
COUNTER=0
while [  $COUNTER -lt 10 ]; do
echo The counter is $COUNTER
let COUNTER=COUNTER+1
done
Added lines 138-202:

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}'
@]

Changed lines 170-184 from:
to:
[@
# 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.
@]
Added lines 139-144:

Creer des fichiers uniques:[@
cur_date=$(date +%Y-%m-%d_%H-%M-%S)


@]
Added lines 140-142:
!! References

http://wiki.bash-hackers.org/syntax/pe
Added lines 80-87:
@]

!! Tests

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

Added lines 2-81:

!! 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

@]

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"

# 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
@]

Changed lines 53-55 from:


to:
!! 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
@]
Changed lines 16-18 from:
#!/bin/bash
count=99

if [ $count -eq 100 ]
to:
if [ conditional expression1 ]
Changed lines 18-27 from:
  echo "Count is 100"
to:
statement1
statement2
.
elif [ conditional expression2 ]
then
statement3
statement4
.
.
.
Changed lines 29-34 from:
  if [ $count -gt 100 ]
  then
    echo "Count is greater than 100"
  else
  echo "Count is less than 100"
  fi
to:
statement5
Added lines 14-29:

La structure if:[@
#!/bin/bash
count=99
if [ $count -eq 100 ]
then
  echo "Count is 100"
else
  if [ $count -gt 100 ]
  then
    echo "Count is greater than 100"
  else
  echo "Count is less than 100"
  fi
fi
@]
Added lines 15-18:
!! Variables
Incrémenter une variable:[@
var=$((var+1))
@]
Added lines 1-37:
Bon, fallait que je m'y mette, voici un petit mémo bash :-)

!! Conditions
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@]


!! 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@]








Page last modified on August 22, 2017, at 04:36 PM EST