Affichage des articles dont le libellé est bash. Afficher tous les articles
Affichage des articles dont le libellé est bash. Afficher tous les articles

1 déc. 2017

[Code] Équivalence Bash vs Powershell


Excellent tableau comparatif entre Bash (scripting shell) et PowerShell (scripting PowerShell
windows) qui peut être intéressant de voir si on connait l'un des deux langages et que l'on souhaite se mettre à l'autre !



Source : http://cecs.wright.edu/~pmateti/Courses/233/Labs/Scripting/bashVsPowerShellTable.html


bashPowerShellDescription
Scripting Basics
Put a "shebang" at the beginning of the file: 
#!/bin/bash

Change permissions on script file to allow execution.
Give the file a ps1 extension. For downloaded scripts, unblock the file under file properties in Windows Explorer.Steps for making scripting files run. In PowerShell, the first time you do scripting, you will need to set the appropriate security settings: run PowerShell as administrator and type set-executionpolicy remotesigned.
source (or) ..shell built-in: execute the commands in a file
echo Stringecho String (or)
Write-Host String
Prints String to the screen. In PowerShell, Write-Hostforces the output to the screen instead of being a return value.
var=0
(No spaces around =)
$var = 0Creates a variable $var. In BASH, do not put whitespace around the equals sign, and do not use a $ in the variable assignment.
let var=$var+5 (or)
var=$(( $var + 5 ))
$var += 5Add 5 to $var
commentcommentA comment
Strings
= !=-eq -ne -ceq -cneString comparisons. In BASH, be sure the strings litereals are in quotes.
"" | gmGet a list of non-static string members
[string] | gm -staticGet a list of static string members
${string#text_to_remove}string.TrimStart("characters")Removes the specified characters/text from the beginning of the string.
${string%text_to_remove}string.TrimEnd("characters")Removes the specified characters/text from the end of the string.  Suppose $fnm == helloThere.txt; then ${fnm%.???} is helloThere
Pattern Matching
grepselect-stringprint lines matching a pattern
sed-replaceperforms string transformations
Booleans and Conditions
true  false$true  $falseBoolean literals
-lt -gt -le -ge -eq -ne-lt -gt -le -ge -eq -neArithmetic relational operators
-likeTrue if a string matches a wildcard pattern
-matchTrue if a string matches a regular expressions
Where-Object { condition }Used to filter input by a condition. Remember that $_ refers to the current object being tested.
-z $var$var -eq $nullTrue if $var is null
-n $var$var -ne $nullTrue if $var is not null (contains one or more characters)
-o -a-or -andLogical or and and
-e fileTest-Path fileTrue if file exists.
! -e file! (Test-Path file)True if file does not exist.
-d filefile.PSISContainerTrue if file is a directory. In PowerShell, if file is not a file variable, be sure to get the file object first with gi.
-s fileTrue if file exists and has a size greater than zero.
file1 -nt file2True if file1 is newer (according to modification date) than file2
file1 -ot file2True if file1 is older (according to modification date) than file2
Control Structures
if [ condition ]
then
   codeblock
fi
if (condition) {
   codeblock
}
If statement. In BASH, be sure to leave a space between the condition and the bracket.
if [ condition ]
then
   codeblock
elif [ condition ]
then
   codeblock
else
   codeblock
fi
if (condition) {
   codeblock
}
elseif (condition) {
   codeblock
}
else {
   codeblock
}
If - else if - else statement
var=0
while [ $var -lt 10 ]
do
   echo $var
   var=$(( $var + 1 ))
done
$var = 0
while ($var -lt 10) {
   echo $var
   $var++
}
Prints numbers 0 through 9.
for ((i=0; i < 10; i++)) do
   echo $i
done
for ($i=0;$i -lt 10; $i++)
{
   echo $i
}
Prints numbers 0 through 9.
for var in $array
do
   codeblock
done
foreach ($var in $array)
{
   codeblock
}
For each loop
continue  breakcontinue  breakLoop controls: continue stops current loop iteration and begins the next; break exits the loop currently being executed.
basename filefile.nameThe name of file without the path. In PowerShell, remember to first get the file object.
dirname filefile.directorynameThe name directory file is in. In PowerShell, remember to first get the file object.
stat -c%s $file (or)
$(stat -c%s $file)
file.lengthThe number of bytes in file. In PowerShell, remember to first get the file object.
file.LastWriteTimeThe last modified time for file. Remember to first get the file object.
files=`ls` (or)
files=$(ls) (or)
files=*
$files = Get-Item *Store a list of the files in the current working directory in $files. In PowerShell, check out the -exclude flag as well as the Get-ChildItem cmdlet.
|  >  >>  2>  2>>|  >  >>  2>  2>>Piping, output and error redirection. In BASH, output redirected to /dev/null is gone. In PowerShell, output redirected to $null is gone.
printArg()
{
   echo $1
}
function printArg
{
   param ($p1)
   echo $p1
}
function to print the first argument to the screen.
return_five()
{
   return 5
}

return_five
echo $?
function return_five
{
   echo 5
  (or)  return 5
}

$value = return_five
echo $value
Function returns 5, which is printed after the function call. In PowerShell, any output in a function that is not caught is returned. The return statement merely ends the function. The return value of a BASH function is stored in the variable $?.
File Information/Operations
lsListing of files. For bash, learn the options of -lisa, -r, -R.
lsListing of files. For PowerShell, learn -f, -r, -filter,and -exclude
treetreeGraphically displays the directory structure of a drive or path.
catcatList the contents of a file on the stdout
moremoreList the contents of a file on the stdout, pausing after each page
mkdirmkdirCreates a directory.
rmdirrmdirDeletes a folder if it is empty
pwdpwdprint working directory
cdcdChange the current directory to the one given as argument.
pushdpushdSaves the current directory name on the stack, and then cd's the one given as argument.
popdpopdPop off the top-most name on the stack, and then cd to it
mvmvMoves or renames files. In PowerShell, check out the -force and -WhatIf flags. In BASH, check out the -f flag.
cp -rcp -rCopies files and directory trees recursively.
cpcpCopies files. In PowerShell, check out the -force and -WhatIf flags. In BASH, check out the -f flag.
rmrmDeletes a file. Check out the -r flag. In PowerShell, check out the -force and -WhatIf flags. In BASH, check out the -f flag.
catcatshow the contents of each file in sequence
moremorepagination
rmrmRemove files
lnLink (hard or soft) to an existing file.
mklinkLink (hard or soft) to an existing file. Type cmd /c mklinkto use it in PowerShell
chmodattribChange file permissions/attributes
icaclsDisplays or modifies access control lists (ACLs) of files
chownicaclsChange ownership of a file. In PowerShell, multiple steps are necessary
umaskget/set the file mode creation mask; packed vector of bits controlling the initial permissions on a newly created file
dumeasureDisk space Used. In PowerShell, try gci . -r | measure -property length -sum
wcMeasure-Objectword count, etc.
odOctal dump of file content. Almost always used with -x for hexadecimal dump
trTranslate/substitute characters; useful in improving interoperability
assocList associations of commands with extensions. Type cmd /c assoc to use it in PowerShell
fileHeuristically determine the type of file content
grepselect-stringSearch for a string in a file's content. For now, learn it without regexp.
findgciLocate a file. By name, etc. For now, learn it without regexp.
whichGives the full path name of a command
whereGives the full path name of a command.  Type cmd /c where to use it in PowerShell
diffdiffList the differences between two text files
cmp, diffcompare, diffshow the differences between two files
gci . -r | sort length -descending | select -first 10get a list of the 10 largest files in the current directory (recursive)
vivimA powerful text editor. For now, learn to edit simple text files with it.
kate, leafpadnotepadSimple text editors.
emacsemacsA very powerful multi-purpose text editor. For now, learn to edit simple text files with it.
Processes
timeMeasure-Commandtimes commands, etc.
pspsshows current processes
gps | sort ws | select -last 5Get a list of the 5 processes using the most memory
gsv | where {$_.Status -eq "Stopped"}Get a list of stopped services
toplike ps, but with continuous updates
bgplace a STOPped process in the background
fgbring a backgrounded process to foreground
killkillkills a running program
ltraceshow lib calls made
straceshow sys calls made
System
manmanshow reference pages
setsetset the values of shell variables
setgvget and show the values of shell variables
envls env:\lists the current environment variables
$PATH$env:paththe search path
linksWWW/News/Mail browser
sftp, filezilla filezillatransfer files securely to/from a remote machine
ssh, putty sshclient, puttyremote login securely
wwho is on the system, and what they are doing
dfgdrshow mounted volumes, etc.

8 nov. 2017

[Code] Batch vs Bash



Tableaux comparatif du code BATCH (Windows .bat) en code SH BASH (.sh) en anglais.

Table N-1. Batch file keywords / variables / operators, and their shell equivalents

Batch File OperatorShell Script EquivalentMeaning
%$command-line parameter prefix
/-command option flag
\/directory path separator
===(equal-to) string comparison test
!==!!=(not equal-to) string comparison test
||pipe
@set +vdo not echo current command
**filename "wild card"
>>file redirection (overwrite)
>>>>file redirection (append)
<<redirect stdin
%VAR%$VARenvironmental variable
REM#comment
NOT!negate following test
NUL/dev/null"black hole" for burying command output
ECHOechoecho (many more option in Bash)
ECHO.echoecho blank line
ECHO OFFset +vdo not echo command(s) following
FOR %%VAR IN (LIST) DOfor var in [list]; do"for" loop
:LABELnone (unnecessary)label
GOTOnone (use a function)jump to another location in the script
PAUSEsleeppause or wait an interval
CHOICEcase or selectmenu choice
IFifif-test
IF EXIST FILENAMEif [ -e filename ]test if file exists
IF !%N==!if [ -z "$N" ]if replaceable parameter "N" not present
CALLsource or . (dot operator)"include" another script
COMMAND /Csource or . (dot operator)"include" another script (same as CALL)
SETexportset an environmental variable
SHIFTshiftleft shift command-line argument list
SGN-lt or -gtsign (of integer)
ERRORLEVEL$?exit status
CONstdin"console" (stdin)
PRN/dev/lp0(generic) printer device
LPT1/dev/lp0first printer device
COM1/dev/ttyS0first serial port

Table N-2. DOS commands and their UNIX equivalents

DOS CommandUNIX EquivalentEffect
ASSIGNlnlink file or directory
ATTRIBchmodchange file permissions
CDcdchange directory
CHDIRcdchange directory
CLSclearclear screen
COMPdiff, comm, cmpfile compare
COPYcpfile copy
Ctl-CCtl-Cbreak (signal)
Ctl-ZCtl-DEOF (end-of-file)
DELrmdelete file(s)
DELTREErm -rfdelete directory recursively
DIRls -ldirectory listing
ERASErmdelete file(s)
EXITexitexit current process
FCcomm, cmpfile compare
FINDgrepfind strings in files
MDmkdirmake directory
MKDIRmkdirmake directory
MOREmoretext file paging filter
MOVEmvmove
PATH$PATHpath to executables
RENmvrename (move)
RENAMEmvrename (move)
RDrmdirremove directory
RMDIRrmdirremove directory
SORTsortsort file
TIMEdatedisplay system time
TYPEcatoutput file to stdout
XCOPYcp(extended) file copy


12 janv. 2016

Supprimer un fichier qui commence par un tiret (ou plus)

Un fichier avait généré un fichier commençant par "--". Mais malencontreusement, la commande rm essaie d'interpréter le tiret...

Heureusement voici un article de l'excellent blog Nixcraft qui explique comment se sortir de cette délicate situation


"I am a new Unix shell user at my university shell server. Accidentally, I had created a file called -foo. Now, how do I remove a file with a name starting with '-' under UNIX-like or Linux operating system?

You can use standard UNIX/Linux rm command. All you have to do is instruct the rm command not to follow end of command line flags by passing double dash -- option before -foo file name.

Many user creates these kind of file accidentally with dashes. If you attempt to remove such file via rm command, UNIX and Linux will attempt to use them as command-line options and the command will display out with an error. So how do you get rid of these files and delete them on a UNIX?


rm command syntax


Use rm command to remove files or directories as follows:
rm -- -foo

OR
rm ./-foo

OR
rm ./-filename
Other options: Unix remove file with dash

Some more options remove the ---- Dashes ---- on a Unix-like system:


rm ./-Foo
rm "./---bar"
rm -- -F
rm -- ---footbal
## Edit file ##
vi  "./--foo"

SOURCE: http://www.cyberciti.biz/faq/unix-linux-remove-strange-names-files/ "

11 janv. 2016

Bash - Afficher un fichier sans les lignes de commentaires

Il est parfois utile d'afficher un fichier sans pour autant afficher la myriade de lignes de commentaire l'accompagnant (en particulier pour les fichiers de configuration de notre OS préféré ;-) ), ainsi qu'en le délestant de ses lignes vides.

Voilà trois façons de procéder.
  •     Grep
  •     Sed
  •     Perl
  •     A lire aussi: Commentaire en bash

Grep

La 1ère à l'aide de "egrep" (ou "grep -E"):
egrep -v '^(#|$)'  /etc/samba/smb.conf

grep -E -v '^(#|$)'  /etc/samba/smb.conf
Là l'exemple se contente de ne pas afficher toutes lignes commençant par un dièse (#) ou par le caractère de contrôle de fin de ligne dollar ($).

S'il s'avérait que le délimiteur de commentaires soit placé non pas en début de ligne mais en retrait (espace ou tabulation), ou que le fichier mêle d'autres caractères délimiteurs comme le point virgule (;), rien ne vous empêche d'embellir votre expression rationnelle comme suit :

grep -E -v '^(#|;|$|[ ]*#)' /etc/samba/smb.conf

Sed

La seconde à l'aide de "sed" :
sed -e '/^[ ]*#/d' -e '/^$/d' /etc/samba/smb.conf
On élimine en premier les lignes commençants par un espace ou un signe dièse, puis on élimine toutes les lignes vides.

Bien entendu comme dans l'exemple précédent vous pouvez étoffer votre commande en incluant d'autres motifs, comme le point virgule, ce qui donnerait :
sed -e '/^[ ]*#/d' -e '/^[ ]*;/d' -e '/^$/d' /etc/samba/smb.conf

Perl

La troisième à l'aide de "perl" :

En fait il s'agit toujours des regex, c'est l'utilitaire qui change.
Qu'il s'agisse de grep, egrep, sed, python, perl, etc. c'est toujours la regex qui fait l'affaire.
Il nous reste seulement à étudier l'implémentation des regex et le moteur utilisé par les utilitaires.
A savoir par exemple qu'un moteur DFA - Deterministic Finite Automation - est plus rapide qu'un moteur NFA - Nondeterministic Finite Automation - .
En revanche le moteur NFA nous permet de mieux peaufiner et diriger la regex pour obtenir le résultat voulu, donc un environement de créativité qu'on ne trouve pas avec un moteur DFA.
perl -ne 'print unless /^\s*[;\$#]|^$/' fichier_config
Les commandes sed et grep utilisent la syntaxe des expressions régulières. Vous pourrez trouver des compléments d'information pour vous familiariser avec cette notion à cette adresse :
phpreg

Source: http://www.commentcamarche.net/faq/3027-bash-afficher-un-fichier-sans-les-lignes-de-commentaires

23 nov. 2015

Timestamp, c'est quoi?

Timestamp ou Horodatage,

"L'horodatage (en anglais timestamping) est un mécanisme qui consiste à associer une date et une heure à un événement, une information ou une donnée informatique. Il a généralement pour but d'enregistrer l'instant auquel une opération a été effectuée." (https://fr.wikipedia.org/wiki/Horodatage)

En effet c'est très pratique enregistrer un fichier à l'instant T (par exemple, la génération d'un rapport)

Le script assez simple ci-dessous permet par exemple de générer un fichier fichier- et traduit le timestamp en langage humain:

#!/bin/sh
HORODATAGE=`date +%s`
FICHIER="fichier-$HORODATAGE.txt"
echo "creation du fichier $FICHIER"
touch $FICHIER
echo "$HORODATAGE humainement parlant correspond à la date du `date -ud @$HORODATAGE`"

ce qui donne :
$ ./temps_t.sh
creation du fichier fichier-1448275999.txt
1448275999 humainement parlant correspond à la date du lundi 23 novembre 2015, 10:53:19 (UTC+0000)

Sinon sur Internet, un bon moyen de décoder du timestamp :
http://tools.semsym.com/index.php?tool=timestamp

ou en encoder
http://tools.semsym.com/index.php?tool=timeencode

19 sept. 2014

-bash-4.1$ gedit Erreur GConf : Le contact du serveur de configuration a échoué ; causes possibles : vous n'avez pas activé le réseau TCP/IP pour ORBit ou des verrous NFS non valides existent suite à un blocage du système. Voir http://projects.gnome.org/gconf/ pour plus d'informations. (Détails - 1: La connexion à la session a échoué : /bin/dbus-launch terminated abnormally without any error message) Erreur GConf : Le contact du serveur de configuration a échoué ; causes possibles : vous n'avez pas activé le réseau TCP/IP pour ORBit ou des verrous NFS non valides existent suite à un blocage du système. Voir http://projects.gnome.org/gconf/ pour plus d'informations. (Détails - 1: La connexion à la session a échoué : /bin/dbus-launch terminated abnormally without any error message) Erreur GConf : Le contact du serveur de configuration a échoué ; causes possibles : vous n'avez pas activé le réseau TCP/IP pour ORBit ou des verrous NFS non valides existent suite à un blocage du système. Voir http://projects.gnome.org/gconf/ pour plus d'informations. (Détails - 1: La connexion à la session a échoué : /bin/dbus-launch terminated abnormally without any error message)


Problème survenu sur une CentOS 6.5 : Résolu en installant dbus-x11

23 sept. 2011

BASH - taille de l'historique et affichage

1.    INTRODUCTION

1.1.    Présentation
Cette procédure indique les manières dont on peut contrôler la taille de l'historique ainsi que sont affichage.

1.2.    Champ d'application
Tout serveur Unix étant muni d'un Bourne Shell (BASH).


2.    APPLICATION DES MODIFICATIONS
Les modifications qui suivent sont à indiquer dans le fichier .bashrc ou .bash_profile de l'utilisateur dont on veut récupérer l'historique.
2.1.    Taille de l'historique
Est gérée par les variables : HISTFILESIZE et HISTFILE.
Etendue de l'historique à 10000, au lieu de 500 par défaut.

HISTFILESIZE=10000

2.2.    Affinage de l'affichage
Nous voulons afficher la date et l'heure des commandes passées.

HISTTIMEFORMAT="[%Y%m%d-%H:%M:%S]"





Différences majeures entre Red Hat 6, 7, 8 et 9

Quelles sont les différences majeures entre RHEL 6, 7, 8 et 9 ? Système de fichiers RHEL 6: Par défaut : ext4. Autres : ext2, ext3 supportés...