Bash stands for Bourne-Again Shell, it is a command line scripting interpretor for UNIX distribution and a shell language.
- most popular shell
- easy line commands
- comes with linux and other OS so no need pre-installation
Bash is the default shell on almost all the Linux distributions but this doesn't mean that linux is going to assume every file we want run is also on bash, that's why we should explicitly specify the shell interpretor path at the beginning of our shell script. See the code below:
#!/bin/bash
##your shell code
In fact, the character sequence "#!" is called Shebang. It is used to tell the system which script interpreter it should use to execute the code contained in the file. This value does not necessarily correspond to Bash, it all depends on the script.We follow up the shebang by providing the full path to the shell.
If you don't know in which shell you are running, type the following line command:
echo $SHELL
it prints the shell interpretor path in which your files are running.
Before we proceed to run shell file,we should give it permission to be executed and then we do:
./filename.sh <arg1>...<argn>
Assignment (and definition if necessary): name=value
Note: ther is no space around "=" sign while assigning value to a variable name, otherwise the system will conside rit as a command name and try to excute it and ends with an error.
number=10
firstName="Jugurta"
count = 0 #error it shouldn't be space around the "=" sign
Access: $name
firstName="Jugurta"
echo "hello" $firstName
Output:
hello Jugurta
In a script, the parameters or arguments, set by the user executing the script, are automatically and always stored in “automatic variables” (automatically filled in by the Shell). These variables are:
- $0 : script name. The content of this variable is invariable.
- $? : return code of the last command (0 if ok)
- $1 to $9 : the possible first 9 arguments passed to the script
- $# : number of arguments
- $* : list of arguments (from $1 separated with space)
- $@ : list of arguments (from $1)
#!/bin/sh
#EXAMPLE
#On suppose qu'on est dans le repértoire courant
currentPath=`pwd`;
if [ ! -d ~/sauvegarde ]
then
mkdir ~/sauvegarde
fi
#pour chaque fichier en argument
for file in $@
do
c=`echo $file| cut -d"." -f2`
#si file est un fichier source c
if [ $c = "c" ]
then
#s'il n'est pas dans le repértoire sauvegarde on le copie
if [ ! -f ~/sauvegarde/$file ]
then
cp $file ~/sauvegarde
#sinon on le compare avec sa copie dèja présente et on le copie en cas de différence
else
numberOfLines=`diff $file ~/sauvegarde/$file | wc -l`
if [ $numberOfLines -ne 0 ]
then
cp $file ~/sauvegarde
else
echo $file already exists
fi
fi
fi
done
- asterisk(*) replaced by any number of any characters;
- ? replaced by exactly any character;
- [ set ] replaced with exactly one character from the given set. The whole is a sequence of characters and/or character ranges. A character range is one character, followed by a dash followed by a character greater than the first in the order of ASCII codes.
- $ replaced with the name that follows by the value of the corresponding variable;
- $( command ) replaced with the standard output obtained when executing the command.
- * protects the following character from expansion;
- 'string' protects the string from expansion;
-
"string" protects the string from expansion except for the characters
$, $ () and .
- < file : read standard input from file;
- > file : write standard output to file;
- 2> file : write standard error to file;
- >> file : concatenate standard output to end of file;
- 2>> file : concatenate standard error output to end of file;
- command_1 | command_2 : redirect standard output of command_1 to standard input of command_2.
#!/bin/sh
cd dir
ls > file (change file content with new content)
ls >> file (concatenate old file content with new one)
#!/bin/sh
if [ -e ~/trash ]
then
ls ~/trash 2> /dev/null
else
cd ~
mkdir trash
fi
Syntax: [ expression ] (or test expression).
- -e : file exists
- -s : file is not empty
- -f : fich is a file
- -d : fich is a directory
- -r : file has permission r (read)
- -w : file has permission w (write)
- -x : file has permission x (execute)
FILE=$1
if [ -e $FILE -a -f $FILE]
then
mv $FILE ~/trash
fi
- -eq : n1 = n2
- -ne : n1 ≠ n2
- -lt : n1 < n2
- -gt : n1 > n2
- -le : n1 <= n2
- -ge : n1 >= n2
a=8
b=7
c=23
if [ a -le b ]
then
echo "yes"
fi
if [c -lt a]
then
echo "Hola"
fi
- -z string : string is empty
- -n string : string is not empty
- string1 = string2 : the 2 strings are identical
- string1 != string2 : the 2 strings are different
name="Jack"
str="Mount"
echo $(expr $name = $str)
Output:
0
- expr1 -a expr2 : and
- expr1 -o expr2 : or
- ! expr : not
i=0
cpt=1
if [ $( expr $i % 2 ) -eq 0 -a i -ne 10 ]
then
cpt=$( expr $cpt + 1 )
i=$( expr $i + 1 )
fi
if <condition>
then
# if condition true
<sequence of commands 1>
else
<sequence of commands 2>
fi
The condition is determined by the return code of an order. The else part is optional.
if <condition_1>
then
<sequence of commands 1>
elif <condition_2>
then
# if condition_1 est false
# and condition_2 true
<sequence of commands 2>
else
# if the two conditions are false
<sequence of commands 3>
fi
for <variable> in <list>
do
<sequence of commands>
done
while <condition>
do
<sequence of commands>
done
<fonction_name>() {
<sequence of commands>
}
-
pwd : displays the current directory (Print Working Directory)
-
cd : change current directory (change directory)
- cd .. : go back to parent directory
- cd / : go to the root directory
- cd : go to the current user's home directory.
- cd - : go to the previously explored directory
-
mkdir dir : creates the dir directory (make directory)
-
rmdir dir : deletes the directory dir if it is empty (remove directory)
-
ls : list files and directories (list)
-
cp : copy files and directories (copy)
- cp file1 file2
- cp file rep
- cp file.
- cp file1 ...file rep
- cp -R rep1 rep2 (rep2 exists or not, copy to rep2 or named rep2 )
-
rm : remove files and directories (remove)
-
mv : moves and/or renames a file or a directory (move)
- mv index.html home.html (renaming)
- mv index.html /home/site/ (move)
- mv index.html /home/site/home.html (move + rename)
-
touch : creates an empty file (or change the last access date of a existing file)
-
cat (concatenate) : concatenates and displays files.
- cat file
- cat file1 file2
-
less (or more) : displays files page by page.
- less file
-
file : identifies the type of a file.
- file file
-
vim (console), emacs, gedit. . . : text editors
-
echo [arguments] : displays its arguments on one line;
-
read name : reads a line and stores it in the variable name;
-
expr expression : displays the value of an arithmetic expression;
-
basename name [extension] : displays the private name of its path part (until the last slash) and its possible extension;
-
dirname name : displays the path part (before the last slash) of name;
-
grep pattern [files ...] : displays the lines of its entries containing the pattern.
-
diff, find, tr, head, tail, cut, sed, sort, ... : and many more...
#!/bin/bash #1 search for the file "fileName" in the entire sub-tree of the indicated 'directory' find ~/directory -name "fileName #2 Search for all files which begin whith a specific pattern "pattern*" in the entire sub-tree of the indicated directory find ~/directory -name "pattern*" #3 Search for all files which contain a pattern "pattern*" in the entire sub-tree of the indicated directory find ~/directory -name "*pattern*
#!/bin/bash find path_of_targeted_directory -type -f -name "*.c" exec grep "main" {} \; #here we are telling bash to search the pattern "main" in every c source file found by find command by associating exec #command to find.The curly braces {} tell bash to execute [grep "main"] when it founds a file with given name.The back slash followed by semi-column tell bash about the end of the exec command.
The tr command is a Linux command-line utility that translates or deletes characters from standard input ( stdin ) and writes the result to standard output ( stdout ).
#The basic tr command syntax is: tr [options] SET1 [SET2]
#example: echo "hello world" | tr o m #output: "hellm wmrld"
#here we change caracter by another one: o->m
- -C : Complements the characters in SET1, including every character in the output except the ones specified.
- -c : Complements the values in SET1. Operations apply to characters that are not in the given set.
- -d : Deletes characters from the SET1 input.
- -s : Squeezes repeated characters specified in the last operand (either SET1 or SET2) and replaces them with a single occurrence of that character.
- -t : Truncates SET1 to the length of SET2.
- -u : Ensures that any output is unbuffered.
- --help : Displays the help file with all available options.
- --version : Displays the program version information.
#More examples:
name="FloRenCE"
echo $name | tr [:upper:] [:lower:]
#output: florence
echo $name | tr [:lower:] [:upper:]
#output: FLORENCE
#the same as:
$name | tr a-z A-Z
#output: FLORENCE
#Remove repeated charcters with s option
echo "hello world 234 34 35" | tr -s " "
echo "hello world 234 34 35" | tr -s [:space:]
#output: hello world 234 34 35
#delete charcaters with d option
echo "Hello , my name is Jugurta ourzik" | tr -d 'u'
#output: Hello , my name is Jgrta orzik
#remove all digits :
echo "your password is: Ab@224#^!" | tr -d [:digit:]
#output: your password is: Ab@#^!
sed allows you to modify or delete part of a character string, for example to replace one character with another in a file, or to delete unnecessary character strings. It is a very powerful tool.
To use sed, you must provide it with a string to process. This string can come from:
- of a file
- of a variable
As a general rule the syntax is of the form sed "s/[searched_occurrence]/[substitution_occurrence]/[behavior]" A simple example of substitution in a list of files: sed "s/[searched_occurrence]/[substitution_occurrence]/g" -i mes_fichiers*
#!/bin/bash
export string="this_is_a_string_of_characters"
echo $string | sed -e "s/_/ /g"
# Will give in response
#output: this is a string of characters
#g stands for glabal, that means change all occurences of _ by space (" ")
sed to replace
#!/bin/bash
#replace the first occurence of the string "unix" by "linux"
sed 's/unix/linux/' file.txt
#Replacing string on a specific line number : You can restrict the sed command to replace the string on a specific line #number. An example is:
sed '3 s/unix/linux/' file.txt
#Duplicating the replaced line with /p flag : The /p print flag prints the replaced line twice on the terminal. If a line does #not have the search pattern and is not replaced, then the /p prints that line only once.
sed 's/unix/linux/p' file.txt
#Printing only the replaced lines : Use the -n option along with the /p print flag to display only the replaced lines. Here #the -n option suppresses the duplicate rows generated by the /p flag and prints the replaced lines only one time.
sed -n 's/unix/linux/p' file.txt
#Replacing string on a range of lines : You can specify a range of line numbers to the sed command for replacing a string.
sed '1,3 s/unix/linux/' file.txt
sed to delete
Deleting lines from a particular file : SED command can also be used for deleting lines from a particular file. SED command is used for performing deletion operation without even opening the file
Examples:
1. To Delete a particular line say n in this example
Syntax:
$ sed 'nd' filename.txt
Example:
$ sed '5d' filename.txt
2. To Delete a last line
Syntax:
$ sed '$d' filename.txt
3. To Delete line from range x to y
Syntax:
$ sed 'x,yd' filename.txt
Example:
$ sed '3,6d' filename.txt
4. To Delete from nth to last line
Syntax:
$ sed 'nth,$d' filename.txt
Example:
$ sed '12,$d' filename.txt
5. To Delete pattern matching line
Syntax:
$ sed '/pattern/d' filename.txt
Example:
$ sed '/abc/d' filename.txt