BASH: Vérifier qu’une commande existe

17/12/2023 Categories: Système Tags: , , Comments off

Comment vérifier qu’une commande existe en Bash ?
Comment vérifier la disponibilité des prérequis d’un script ?

Une méthode permettant de vérifier qu’une commande existe consiste à tester le retour de « command -v <commande_a_tester> » :

fhh@mafalda ~ $ command -v ls
alias ls='ls --color=auto'
fhh@mafalda ~ $ echo $?
0
fhh@mafalda ~ $ command -v ls > /dev/null && echo "ls existe" ls existe
 

Si la commande existe et est accessible via le PATH ou au chemin spécifié, « command -v » retourne « 0 », sinon, le retour est supérieur à « 0 » :

fhh@mafalda ~ $ command -v youhou
# youhou n'existe pas dans le PATH ou comme commande interne :
fhh@mafalda ~ $ echo $?
1
fhh@mafalda ~ $ command -v ../../usr/bin/date
# date est accessible au chemin spécifié :
fhh@mafalda ~ $ echo $?
0

Lire la suite…

Categories: Système Tags: , ,

BASH : Suppression des accents, cédilles, etc

17/12/2023 Categories: Système Tags: , , , Comments off

Comment supprimer les accents, cédilles, etc, dans une chaine de caractères ?

Méthode classique : la substitution

La suppression des caractères accentués et autres cédilles peut être effectuée, en Bash, en utilisant « sed » ou « tr » :

fhh@aaricia ~ $ _str="Une chaine avec des é, des Ù, des À, des ç et des œ"
fhh@aaricia ~ $ echo $_str | sed 'y/áàâäçéèêëîïìôöóùúüñÂÀÄÇÉÈÊËÎÏÔÖÙÜÑ/aaaaceeeeiiiooouuunAAACEEEEIIOOUUN/' Une chaine avec des e, des U, des A, des c et des œ

La méthode est fonctionnelle mais sous entend que tous les caractères à substituer aient été définis. Dans l’exemple, le « œ » n’a pas été remplacé car aucun caractère de remplacement ne lui est alloué.

Autre problème de cette méthode, remplacer une lettre par deux autres tel que « œ » par « oe » ou le « ß » allemand par « ss » nécessite la définition de règles particulières à chaque cas.

Ce sont ces raisons qui nous poussent à éviter cette méthode au profit de la conversion de chaines de caractères.

Méthode recommandée : la conversion

Plus complète, la méthode de conversion présente en sus l’avantage d’être plus concise.

« iconv » est utilisé pour « convertir » la chaine de caractères du format de base, UTF-8 dans l’exemple (option « -f » pour « from »), vers le format ASCII (option « -t » pour « to »).

Avec l’option « TRANSLIT », si un caractère ne peut être transcrit dans le format de destination, il est converti en une chaine de caractère équivalente.

fhh@aaricia ~ $ _str="Une chaine avec des é, des Ù, des À, des çÇ et des œ"
fhh@aaricia ~ $ echo $_str | iconv -f utf8 -t ascii//TRANSLIT Une chaine avec des e, des U, des A, des cC et des oe

La méthode fonctionne sur un large panel de caractères :

fhh@aaricia ~ $ echo "\"ß\"" | iconv -f utf8 -t ascii//TRANSLIT "ss"
fhh@aaricia ~ $ echo "āáǎàēéěèīíǐìōóǒòūúǔùǖǘǚǜĀÁǍÀĒÉĚÈĪÍǏÌŌÓǑÒŪÚǓÙǕǗǙǛ" | iconv -f utf8 -t ascii//TRANSLIT aaaaeeeeiiiioooouuuuuuuuAAAAEEEEIIIIOOOOUUUUUUUU

et peut être utilisée sur des fichiers :

fhh@aaricia ~ $ cat myfile.txt Une chaine avec des é, des Ù, des À, des ç et des œ   et même des "ß"
fhh@aaricia ~ $ iconv -f utf8 -t ascii//TRANSLIT < myfile.txt > noaccents.txt
fhh@aaricia ~ $ cat noaccents.txt Une chaine avec des e, des U, des A, des c et des oe   et meme des "ss"
 
Categories: Système Tags: , , ,

Rsync : Sync Files/Directories

16/12/2023 Categories: Système Tags: , , , Comments off

Copy files or directories from one location to an another host by rsync.

If you’d like to set rsync automatically by cron or others, it need to configure like follows because authentication is required without settings. For example, Copy files or directories under the [/root/work] on dlp.srv.world to [/home/backup] on www.srv.world.

[1] Configure on source host.

root@dlp:~# apt-get -y install rsync
root@dlp:~# vi /etc/rsync_exclude.lst
# specify files or directories you'd like to exclude to copy
test
test.txt

[2] Configure on destination host.

root@www:~# apt-get -y install rsync
root@www:~# vi /etc/default/rsync
# line 8: change
RSYNC_ENABLE=true
root@www:~# vi /etc/rsyncd.conf
# create new
# any name you like
[backup]
# destination directory to copy
path = /home/backup
# hosts you allow to access
hosts allow = 10.0.0.30
hosts deny = *
list = true
uid = root
gid = root
read only = false
root@www:~# mkdir /home/backup
root@www:~# systemctl start rsync

[3] It’s OK. Execute rsync on Source Host like follows.

root@dlp:~# rsync -avz --delete --exclude-from=/etc/rsync_exclude.lst /root/work/ www.srv.world::backup
# Add in cron if you'd like to run reguraly
root@dlp:~# crontab -e
# for example, run at 2:00 AM in a day
00 02 * * * rsync -avz --delete --exclude-from=/etc/rsync_exclude.lst /root/work/ www.srv.world::backup
Categories: Système Tags: , , ,

Bash: How do I get the command history in a screen session?

16/12/2023 Categories: Système Tags: , , Comments off

If I start a screen session with screen -dmS name, how would I access the command history of that screen session with a script?

Using the , the last executed command appears, even in screen.

ANSWER:

I use the default bash shell on my system and so might not work with other shells.

this is what I have in my ~/.screenrc file so that each new screen window gets its own command history:

Default Screen Windows With Own Command History

To open a set of default screen windows, each with their own command history file, you could add the following to the ~/.screenrc file:

screen -t "window 0" 0 bash -ic 'HISTFILE=~/.bash_history.${WINDOW} bash'
screen -t "window 1" 1 bash -ic 'HISTFILE=~/.bash_history.${WINDOW} bash'
screen -t "window 2" bash -ic 'HISTFILE=~/.bash_history.${WINDOW} bash'

Ensure New Windows Get Their Own Command History

The default screen settings mean that you create a new window using Ctrl+a c or Ctrl+a Ctrl+c. However, with just the above in your ~/.screenrc file, these will use the default ~/.bash_history file. To fix this, we will overwrite the key bindings for creating new windows. Add this to your ~/.screenrc file:

bind c screen bash -ic 'HISTFILE=~/.bash_history.${WINDOW} bash'
bind ^C screen bash -ic 'HISTFILE=~/.bash_history.${WINDOW} bash'

Now whenever you create a new screen window, it’s actually launching a bash shell, setting the HISTFILE environmental variable to something that includes the current screen window’s number ($WINDOW).

Command history files will be shared between screen sessions with the same window numbers.

Write Commands to $HISTFILE on Execution

As is normal bash behavior, the history is only written to the $HISTFILE file by upon exiting the shell/screen window. However, if you want commands to be written to the history files after the command is executed, and thus available immediately to other screen sessions with the same window number, you could add something like this to your ~/.bashrc file:

export PROMPT_COMMAND="history -a; history -c; history -r; ${PROMPT_COMMAND}"
Categories: Système Tags: , ,

Scripts shell de sauvegarde

15/12/2023 Categories: Système Tags: , , , Comments off

Une des façons les plus simples de sauvegarder un système utilise un script shell. Par exemple, un script peut être utilisé pour configurer les répertoires à sauvegarder et transmettre ces répertoires comme arguments à l’utilitaire tar, ce qui crée un fichier d’archive. Le fichier d’archive peut ensuite être déplacé ou copié dans un autre emplacement. L’archive peut également être créée sur un système de fichiers distant tel qu’un montage NFS.

L’utilitaire tar crée un fichier d’archive de plusieurs fichiers ou répertoires. tar peut également filtrer les fichiers par le biais des utilitaires de compression, réduisant ainsi la taille du fichier d’archive.

Categories: Système Tags: , , ,