Certain Bash options are well-known and frequently used. For example, many start their scripts with
set -o xtrace
for debugging,
set -o errexit
to exit on error, or
set -o errunset
to exit if a called variable is not set.
But there are many other options. Sometimes they are described too confusingly in the manuals, so I've gathered here some of the most useful ones, with explanations.
Note: on Mac, an older version of bash (3.x instead of 4.x) might be installed, where not all these options are available. In this case, refer to ou .
set ou shopt?
There are two ways to set bash options: from a script or from the command line. You can use built-in commands set et shopt. Both affect the behavior of the shell, doing largely the same thing (with different arguments), and differ in their . Options set are inherited or borrowed from the options of other shells, while options shopt are created in bash.
If you want to see the current options, run:
$ set -o
$ shopt To activate an option in set you can use either long or short syntax:
$ set -o errunset
$ set -eThe effect is the same.
To disable an option, you need to use a plus instead of a minus:
$ set +eFor a long time, I couldn't remember this syntax, as the logic seems wrong (minus enables the option, while plus disables it).
Dans shopt for enabling and disabling options (more logically) use flags -s (set) and -u (unset):
$ shopt -s cdspell # <= on
$ shopt -u cdspell # <= offChanging directories
There are several options that help work with directories.
1. cdspell
With this setting, bash will start understanding typos and will carry you to the folder whose name you typed incorrectly.
$ shopt -s cdspell
$ mkdir abcdefg
$ cd abcdeg
abcdefg
$ cd .. I have used this option for many years, and very rarely (maybe once a year) it makes a very strange decision. But in the remaining days cdspell saves time, literally every day.
2. autocd
If you are not willing to put up with the inefficiency of repeatedly typing cd, you can enable this option to move to folder X if command X does not exist.
$ shopt -s autocd
$ abcdefg
$ cd ..Combined with autocompletion, this allows quick jumps between folders:
$ .\/abc[TAB][RETURN]
cd -- .\/abcdefg Just don't name the folder rm -rf * (yes, by the way, it's possible).
3. direxpand
This is a cool option that expands environment variables when you press Tab:
$ shopt -s direxpand
$ .\/[TAB] # se remplace par...
$ \/full\/path\/to\/current_working_folder
$ ~\/[TAB] # se remplace par...
$ \/full\/path\/to\/home\/folder
$ $HOME\/[TAB] # se remplace par...
$ \/full\/path\/to\/home\/folderSortie propre
4. checkjobs
Ce paramètre empêche la sortie de la session s'il y a des tâches en cours d'exécution en arrière-plan.
Au lieu de quitter, une liste des tâches non terminées est affichée. Si vous souhaitez quand même quitter, entrez à nouveau exit.
$ shopt -s checkjobs
$ echo $$
68125 # <= ID du processus pour le shell
$ sleep 999 &
$ exit
Il y a des tâches en cours d'exécution.
[1]+ En cours d'exécution sleep 999 &
$ echo $$
68125 # <= ID du processus pour le shell le même
$ exit
Il y a des tâches en cours d'exécution.
[1]+ En cours d'exécution sleep 999 &
$ exit
$ echo $$
$ 59316 # <= cette fois-ci, l'ID du processus a changéSuperpouvoirs de substitution
5. globstar
Cette option vous donne des superpouvoirs de substitution ! Si vous entrez :
$ shopt -s globstar
$ ls **alors le shell affichera tous les répertoires et sous-répertoires de manière récursive.
En combinaison avec direxpand vous pouvez rapidement parcourir tout ce qui se trouve en dessous dans la hiérarchie :
$ shopt -s direxpand
$ ls **[TAB][TAB]
Afficher toutes les 2033 possibilités ? (y ou n) 6. extglob
Cette option active des fonctionnalités souvent associées aux expressions régulières. Cela peut être très utile :
$ shopt -s extglob
$ touch afile bfile cfile
$ ls
afile bfile cfile
$ ls ?(a*|b*)
afile bfile
$ ls !(a*|b*)
cfileIci, les modèles sont placés entre parenthèses et séparés par une barre verticale. Voici les opérateurs disponibles :
? = соответствует нулю или одному вхождению заданных шаблонов ! = показать всё, что не соответствует заданным шаблонам * = ноль или более вхождений + = одно или более вхождений @ = ровно одно вхождение
Protection contre les accidents
7. histverify
Au début, il peut être un peu effrayant d'utiliser le lancement rapide des commandes à partir de l'historique avec les abbréviations !! et !$.
L'option histverify permet de voir d'abord comment Bash interprète la commande avant qu'elle ne soit réellement exécutée :
$ shopt -s histverify
$ echo !$ # <= En appuyant sur Entrée, la commande ne s'exécute pas
$ echo histverify # <= Elle est d'abord affichée à l'écran,
histverify # <= puis elle s'exécute 8. Noclobber
Encore une fois, pour protéger contre les accidents, notamment contre l'écrasement d'un fichier qui existe déjà avec l'opérateur de redirection (>). Cela peut être catastrophique si vous n'avez pas de sauvegarde.
L'option set -C interdit une telle écriture. Si nécessaire, vous pouvez contourner la protection avec l'opérateur >|:
$ touch afile
$ set -C
$ echo something > afile
-bash: afile: impossible d'écraser le fichier existant
$ echo something >| afile
$Source : habr.com
