Discord Server Red Security Twitter Donation to Red Security Red Security Youtube Channel Red Security Tumblr Profile
Login or Register to Hide ads and Accessing all features on the forum
Thread Rating:
  • 6 Vote(s) - 2.17 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Tutorial Scripting Courses
The scripting tutorial consists of three main parts

The first part consists of command line and scripting prerequisites

In the second part, we start scripting from the beginning and move on to the intermediate level (second page)

And in the third part, we will follow the basics related to advanced scripting

Please do not Send any spam and if so, mention it in a private message
I have made a forum for you course so you can continue using this section until you finish Big Grin

Good luck.
* Thankful to Allah *
Part One 1

One way to connect to the CLI or command line interface is to use Linux without a desktop.

Just like in the old days of Linux when you were just dealing with a visual console environment

We can also use Alt + Ctrl + F1 / F7 to visually console the graphical environment.

Each of the Fs provides us with a separate visual console environment

Which are connected directly to the deeper thigh and we can even log in at the same time with different users

Each of these separate console environments has its own number that can be seen in tty

For example, when you open Alt + Ctrl + F2 with your second console environment

And you log in with the same user or another user, you can see the value of tty2 in the first line

Which shows that you are in the second console environment

To shift between tty, use the same Alt + Ctrl + F with the desired tty number

In this case F1 (return from the second console environment (with a value of tty2) to the primary consulate environment (with a value of 1 tty))

After shifting between consoles, all consoles remain in login mode with any user they have and the actions performed with them remain intact, which creates considerable coherence and flexibility.

We can also use text mode console terminal in console environments

Use to customize the console environment

Using the setterm command

For example, I will put a few cases, but of course you can see the various list of setterm commands with help.
setterm -background black white red blue green yellow magenta cyan
Change the background color to one of the colors I wrote the name
setterm -foreground green
Change the text color to green (or whatever color you write its name on)
inversescreen on or off
Invert background and text colors
Save changes
Return to default

The next way to connect to Shell is to use graphical terminals from inside the desktop environment

These terminals work on the console but from within the desktop graphical environment

There are several terminals in the graphical environment, each of which has its own options, but because the main job is done by the shells and these terminals are just interfaces, the use of each of them is more a matter of taste.

Below I make a list of their most used with their sites for fans

Eterm    http://www.eterm.org
Final    Term http://finalterm.org
GNOME    Terminal https://help.gnome.org/users/gnome-terminal/stable
Guake    https://github.com/Guake/guake
Konsole    Terminal http://konsole.kde.org
LillyTerm    http://lilyterm.luna.com.tw/index.html
LXTerminal    http://wiki.lxde.org/en/LXTerminal
mrxvt    https://code.google.com/p/mrxvt
ROXTerm    http://roxterm.sourceforge.net
rxvt    http://sourceforge.net/projects/rxvt
rxvt-unicode    http://software.schmorp.de/pkg/rxvt-unicode
Sakura    https://launchpad.net/sakura
st    http://st.suckless.org
Terminator    https://launchpad.net/terminator
Terminology    http://www.enlightenment.org/p.php?p=about/terminology
tilda    http://tilda.sourceforge.net/tildaabout.php
UXterm    http://manpages.ubuntu.com/manpages/gutsy/man1/uxterm.1.html
Wterm    http://sourceforge.net/projects/wterm
xterm    http://invisible-island.net/xterm
Xfce4 Terminal    http://docs.xfce.org/apps/terminal/start
Yakuake    http://extragear.kde.org/apps/yakuake

Well, friends, this part was mostly about the introduction of the first part and the acquaintance of those who are interested in the console

That's why I tried to explain it very briefly

Part One 2

The shell that the system starts using depends on the configuration of the logged in user

The / etc / passwd file contains a list of system users that has the configuration information in front of each user.

Below is an example of the passwd file values in the etc directory

rednaxela:X:501:501:red naxela:/home/rednaxela:/bin/bash
Each passwd file value has seven fields that are separated by (Smile

In the following sections we will talk more about each of these fields, but in this section we will focus on the seventh field.

With the shell name and directory directory, this is the shell that is given to that user by default after logging in.

In this example, the rednaxela user is placed on the bash shell after logging in

Most Linux uses the powerful bash shell by default, which is one of the main shells for scripting.

For this reason, we base the core of this collection on this shell, and after the end of the third section, we take a brief look at the other shells.

Interact with bash manual with man command:

Manual pages are pages that have the most comprehensive descriptions and instructions for loose objects.

For example, you can test a command by learning how it works and the options of that command

man jobs

man -k download

In the first command, we get the manual pages using the man command for the jobs command

But the second command that executes the man command with the k-option, this option can be used to discover commands that you do not know

For example, we want to download a file using the command line, but we do not know what command to use to download

With the man -k download command, the commands related to download are displayed to us

Use the letter q to exit the manual pages

For more information about the man command, you can use the man man command for itself

You can use the obtained information to identify the different output parts of the man command

System file and related commands:

Note the difference between Windows and Linux partitions

As you can see in the example below, Linux does not follow the drive system used by Windows and has an integrated internal structure in terms of partitioning.

The point to keep in mind in scripts is that Linux paths, unlike Windows, use slash / not backlash \
And Linux, unlike Windows, is case sensitive



Directory values /

boot = boot directory (where boot files are kept)

dev = device directory (where Linux generates and maintains device nodes)
etc = system configuration (where system configuration files are stored)
home = Home directory (where Linux generates and maintains the user directory)
lib = Directory Liberation (where Linux holds the libraries of its system and application libraries)
media = media directory (a common place for media removable from the system)
mnt = Mount Directory (another common place to mount removable media)
opt = Optional directory (storage of data and software packages of third-party software)
proc = directory directory (where hardware and process information is stored)
bin = directory binary (where many GNU's user-level tools are stored)
root = root directory (where the home directory and root user data are stored)
sbin = directory binary system (where many GNU admin level tools are stored)
run = directory directory (where run time data is stored)
srv = directory service (where data related to the services provided by the system is stored)
sys = directory system (where data related to hardware information is stored)
tmp = Template directory (where Tempori files (discussed in full in the relevant chapter) can be generated and stored)
usr = Binary Directory User (where tools and GNU user level data files are stored)
var = Aber directory (where files with variable values are stored, such as log files)

For example, when you log in to Shell, by default you are in the top directory in the home directory, but there is also another directory called Accounton.

Command line commands:

cd /home/rednaxela

cd ..

The cd command is used to browse the file system

Values such as (.) Or (..) refer to the current directory and the higher directory, respectively.



The pwd command is used to display the address where we are in the file system
In this example, the output of the pwd command says we are in the root / books / path

ls -F -R -a -l
ls *.txt
ls scri??
ls go[a-p]d
ls b[!a]d

The ls command is used to view a list of values in a directory
Which has a variety of options, a few of which I mentioned as an example, the options can be used individually or more, or even sand integration such as ls -alF

The F-option distinguishes files from directories
The R option lists all the contents of the directory with all the values they have until the end.
Option a- also displays hidden values in the list
The l-option shows the output list with information about each of the values
Values such as file access level for users
File owner name
File group name
File size value
The last time it was modified and ...

The ls command can also be used for the lists we want
Like ls * .txt, which lists any file with the last four characters named (t & x & t &.)
Or ? Who says accept everything instead of me
Or [a-p], which says accept any character from a to p instead of me
Or [a!] That says accept any other character instead of a

You can use these few simple examples except the ls command in countless places
Of course, you will get acquainted with more models in the following

touch filename
touch script
touch abc.txt
touch /home/rednaxela/zzzz.sh

The touch command is used to create an empty file

In the example above, you can see how to use it and its features

cp file file2
cp /root/file /home/rednaxela/file
cp file /root/books/file
cp /home/rednaxela/books/file .

The cp command is used to copy files

In the first example, a file was copied to the same directory, so we changed its name
In the second example, because we ourselves were not copied in any of the origin and destination routes
We wrote the file name, both at the source and at the destination, along with the full path
In the third example, because we were in the directory directory, we wrote the file name without the source address
And the fourth example, as we said before, the character (.) Refers to our current directory, so to copy the file to where we are, we wrote the source path and put the character (.) Instead of the destination path (where we are).

We can also use the i-option, which, if there is a file with the same name in the destination address, will be tested before copying the values of that file.
Using the R-option we can copy all the contents of a directory

ln -s /target-file-name /shortcut-file-name

The ln command with the s-option is used to create shortcuts

mv /home/rednaxela/file1 /home/rednaxela/file2

mv file1 /root/books/

The mv command is used to transfer the file and rename the file
In the first example (rename to file2) the name is changed
In the second example (transfer to the books directory) the file is transferred
In the mv command, like the cp command, we can use the i- or R- option

rm file-name

rm -R directory-name

With the rm command and select the file, the desired file will be deleted

Using the R-option we can delete a directory with all its values

mkdir directory-name

mkdir -P dir/dir/dir/directory-name

Using the mkdire command we can create a directory

By adding the P-option we can create nested directories with one command

rmdir directory-name

The rmdir command is used to delete empty directories

tree directory-name

The tree command is used to see the tree structure of a directory

(Depict all values layer by layer)

file file-name

The file command specifies the type of file you give it based on the value of the file

cat file-name
cat -n file-name
cat -b file-name

The cat command opens the file you gave it (not run)
Option n- The first of each line is a Mizar number coming down in order
Option b - Applies numbering only to lines that have values first

more file-name

The more command works the same as the cat command, but the user is more friendly
And displays the output value in sections and percentages
Compared to cat, it is more dynamic and increases the user's scanning power

less file-name

The less command is an advanced more model, the most notable of which is that

Opens the file before it is fully read, which means that as soon as it is executed, it displays the amount of data it has received, and if the file is large, it does not wait for the user to read the entire file.

tail file-name
tail -n 5
tail -5
tail -f

The tail command reads the last ten lines of the file by default
With the n- option and the request number, the number of lines at the end of the file or directly entering the requested number after (-)

We can change this value
The interesting thing about this command is the f-option, which makes the command session active even when a program is using the desired file.
This causes the changes to be displayed live as soon as the file is changed

head file-name
head -n 6
head -6
head -f

The head command of the model is the opposite of the tail command, which reads the first ten lines of the file

In other cases, it works exactly like the tail command
Reply 1
Thank you for this my friend. Can't wait for part 3.
Part One - Part 3

Continuation of the command line command (Linux system management)
One of the most important parts of Linux management is monitoring the active agents in the system
Which we review related commands


When a program runs on the system, it shows itself as a process
To see what processes are running on the system, we use the ps command
Which can give us information about each of them while showing the processes
Here I give an example of some of its interesting options

Option A - Show all processes
Option M- Display security information about processes
Option f-list view (full format)
Option l- Show as long list (more info)
The forest-- option, which is one of the GNU Long parameters, is used to visualize the relationship between processes.

I will list some of the values that the ps command can give us

Uid field: Relates to the user who enabled the process
Pid field: process ID code (one code unique to each process)
Ppid field: If one process is enabled by another process, pid displays the initial process
Stime field: The time system in which the process is enabled
TTY field: Indicates in which TTY each process is enabled
Cmd field: The name of the program of each process

As you can see, the ps command works great on its own, and the dynamics of this command are not limited to our small example.
But if your goal is to monitor the process of processes that are interrupted
You must use the top command

The top command, like ps, lists processes and information for us
But it does this in real-time, which helps us reach our goal

The first section displays the general information output of the system
First line: the current time, when the system is high, shows the number of logged in users and the average load
The second line shows the general information of the processes
For example: the total number of processes, how many active processes there are, how many processes stop, how many processes are asleep now, and how many processes become zombies
Zombies: Processes that have been completed but processes that have enabled them have not yet been answered
The third line shows general information about the CPU
And the last two lines are about system memory status, the first line is physical memory status, and the second line is swap memory

The second part of the command also contains process information, such as the ps command

kill 3940
killall http*
The kill and killall commands are used to stop the process

In the first example, we pid a process that is 3940 as a value to the command to stop that process
In the second example, I tell the killall command to stop any process that starts with http

mount -t ntfs /dev/sdb1 /media/disk
umount directory device
As we talked about earlier, Linux puts the entire filesystem in a reference directory (/)
Before you can use a media disk, you must insert it into the directory system, which is called mounting.
You need root access to do this
(Of course, this applies to those removable media for which this does not happen automatically, which does not include common cases)

By entering the mount command alone, a list of mounted devices is displayed, along with their path, their file system type, and their access level status.

In the first example, we mounted a flash drive with the ntfs filesystem type in the device address and the specified media address, respectively.
Of course, by default, only the same root user has access to the mounted media, which can change the access level

In the second example, we used the umount command to unmount

df -h
We use the df command to see the free space of all devices (internal and external)

The h-option displays the output values in meg and gig, etc., which is easier to understand

du -h
The du command, unlike the df command, displays the values for the space used

The h-option is the same as the qibla example option

sort file1
sort -n file1
sort -M file1
sort -r file1
sort -t ':' -k 3 /etc/passwd
The sort command is used to sort values
The n-option is used to sort by number order
The M-option is used to sort by the order of the lunar months (for cases where the names of the values have the name of the month, such as log files)
The r-option is used to reverse the current order of values
But the interesting combination of t- and k- that in the first step selects a character as a separator and in the second step selects the desired block between the created blocks, in our example the third selected block, from among the blocks That created the character (Smile

grep root passwd
grep -e red -e blue file-name
grep -v xxxx file-name
grep -n
grep -c
We use the grep command to search and interact with values and files
In the first example, by specifying the root search pattern for the passwd file, we use the grep command to display any line between the values of the passwd file that had a Maru pattern.
The e-option is used to specify multiple patterns, in our example the red and blue patterns are specified
The v-option tells the command to display all file values except for the parts that have our pattern
The n-option also displays the line number that has the value of the Murrow pattern
Option c- Instead of displaying values, displays the number of lines that have a pattern

The gzip command is used to zip the file
The gzcat command is used to display the values of the zip file
The gunzip command is used to unzip values

tar -cvf test.tar test/ test2/
tar -tf test.tar
tar xvf test.tar
tar -zxvf file-name.tgz.
The tar command is used to create tar zip files that are part of the usual zip files
The c-option is used to create the file
The v-option is used to display the process
The f-option is used to specify the output file
The x-option is used to extract zip file values
In the first example we create a zip file called test.tar that receives the values of the test and test2 folders
In the second example we see the value of the file created in the first example without extracting the file
In the third example, we extract the file
In the fourth example, we extract the file, which of course is not related to the default format, for example, it is used to extract the files.

In the following, I have given you a list of frequently used commands that you have seen forgiveness so far, and you will see the rest in the following sections, depending on the topic of that section.

head      Displays the fi rst portion of the specifi ed fi le’s contents
help      Displays the help pages for bash built-in commands
killall      Sends a system signal to a running process based on process name
kwrite     Invokes the KWrite text editor
less     Advanced viewing of fi le contents
link     Creates a link to a fi le using an alias name
ln     Creates a symbolic or hard link to a designated fi le
ls     Lists directory contents
makewhatis     Creates the whatis database allowing man page keyword searches
man     Displays the man pages for the designated command or topic
mkdir     Creates the specifi ed directory under the current directory
more     Lists the contents of the specifi ed fi le, pausing after each screen of data
mount     Displays or mounts disk devices into the virtual fi lesystem
mv     Renames a fi le
nano     Invokes the nano text editor
nice     Runs a command using a different priority level on the system
passwd     Changes the password for a system user account
ps     Displays information about the running processes on the system
pwd     Displays the current directory
renice     Changes the priority of a running application on the system
rm     Deletes the specifi ed fi le
rmdir     Deletes the specifi ed directory
sed     Streams line editing using editor commands
sleep     Pauses bash shell operation for a specifi ed amount of time
sort     Organizes data in a data fi le based on the specifi ed order
stat     Views the fi le statistics of the specifi ed fi le
sudo     Runs an application as the root user account
tail     Displays the last portion of the specifi ed fi le’s contents
tar     Archives data and directories into a single fi le
top     Displays the active processes, showing vital system statistics
touch     Creates a new empty fi le or updates the timestamp on an existing fi le
umount     Removes a mounted disk device from the virtual fi lesystem
uptime     Displays information on how long the system has been running
useradd     Creates a new system user account
userdel     Removes an existing system user account.
usermod     Modifi es an existing system user account
vi     Invokes the vim text editor
vmstat     Produces a detailed report on memory and CPU usage on the system
chage     Changes the password expiration date for the specified system user account
chfn     Changes the specifi ed user account’s comment information
chgrp     Changes the default group of the specifi ed fi le or directory
chmod     Changes system security permissions for the specifi ed fi le or directory
chown     Changes the default owner of the specifi ed fi le or directory
chpasswd     Reads a fi le of login name and password pairs and updates the passwords
chsh     Changes the specifi ed user account’s default shell
clear     Removes text from a terminal emulator or virtual console terminal
compress     Original Unix fi le compression utility
coproc     Spawns a subshell in background mode and executes the designated command
cp     Copies the specifi ed fi les to an alternate location
crontab Initiates the editor for the user’s crontable fi le, if allowed
cut     Removes a designated portion of each specifi ed fi le’s lines
date     Displays the date in various formats
df     Displays current disk space statistics for all mounted devices
du     Displays disk usage statistics for the specifi ed fi le path
emacs     Invokes the emacs text editor
file     Views the fi le type of the specifi ed fi le
find     Performs a recursive search for fi les
free     Checks available and used memory on the system
gawk     Streams editing using programming language commands
grep     Searches a fi le for the specifi ed text string
gedit     Invokes the GNOME Desktop editor
getopt     Parses command options including long options
groups     Displays group membership of the designated user
groupadd     Creates a new system group
groupmod     Modifi es an existing system group
gzip     The GNU Project’s compression using Lempel-Ziv compression
whereis     Displays a designated command’s fi les, including binary, source code, and man pages
which     Finds the location of an executable fi le
who     Displays users currently logged into system
whoami     Displays the current user’s username
xargs     Takes items from STDIN, builds commands, and executes the commands
zip     Unix version of the Windows PKZIP program

Part One - Part 4

Now that you are somewhat familiar with the basic command line commands, it is time to take a deeper look at the shell
To better understand it, we need to review the Basic Command Line Interface (CLI) cases

A shell is not just a command line interface, but a program running complex interactions
Executing Shell commands in certain situations may seem a bit misleading, as can some scripts, which can be understood by understanding how Shell works and its relationships.

In this section, you will get acquainted with the shell process and the emergence of sub-shells and their relationship with shell prints.

Be sure to mention that in the previous sections we talked about the default shell for each user, which in the configuration of each user this value can vary.
(Seventh field of passwd file values with the default bin / bash / shell value of the user (show here) and its address)
When you log in to the visual console environment, or when you open a terminal in the graphical environment, the default shell I described will be activated for you.
But ...
But this is not the only default shell of your system
There is another default shell called system shell default, which is used for system scripts, such as those needed in a startup.
This default shell is in the bin / sh / path

In some Linuxes you can see the following example in which the default system default is set using a link.

$ ls -l /bin/sh
lrwxrwxrwx. 1 root root 4 Mar 20 15:05 /bin/sh -> bash
Of course, you should note that not all Linux use a shell for both shell system default and interactive shell default.

And each of the two default shells may be set to a different shell, as in the example below

$ cat /etc/passwd

$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 Apr 22 12:33 /bin/sh -> dash
Differences in default shells can lead to our script not working properly
(If the default system shell of the system running the script is different from the shell with which the script was written)

For this reason, we always specify in the first line of script the type of shell that is going to execute (related to the second part of the tutorial)

Although the default shells are changeable, you do not normally have to use the interactive shell shell by default. In the same console environment, you can read each shell to receive that STDIN shell (in the second section, you will learn about STDIN ٬ here I mean the input values) and work with that loose from that moment

For example, note below, read in the shell terminal environment, pay attention to the output of the command, this output does not mean (nothing and no output)
From this point on, enter any command. Shell Dash will take that command
Like the exit command that took the shell shell and closed itself accordingly, and therefore the terminal did not close and you see the prompt sign (which means you went back to the same shell with which you read the shell shell)
$ /bin/dash

$ exit
An overview of the parent shell relationship with the child shell or the same subshell

The shell that you get after logging in to the console environment, or from the terminal in the graphical environment, is considered a print shell or an initial shell
When you open another shell in a loose environment (either direct or indirect)
That secondary shell, Child Shell or Sub Shell

After opening a subshell, nothing special is displayed to show the relationships between the shells, so we use the ps command with the f-option.
In the example below you can see an example of the output of the command before executing the subshell and after

$ ps -f
501 1841 1840  0  11:50 pts/0 00:00:00 -bash
501 2429 1841  4  13:44 pts/0 00:00:00 ps -f
$ bash
$ ps -f
501 1841 1840  0  11:50 pts/0 00:00:00 -bash
501 2430 1841  0  13:44 pts/0 00:00:00 bash
501 2444 2430  1  13:44 pts/0 00:00:00 ps -f
Pay attention to the output of the first command, the two processes show the first bash-the second ps command
If you look at the ppid (print process number) of the ps command, you will see the pid (process number), which means that the parent process from which the ps command process originated belongs to Bash.

With the same interpretations in the output of the second ps command
(Which is typed after the bash command, which means that the ps command is entered inside the new shell that was opened)
We see that there are three processes, pay attention to the ppid of the second process (new shell) You see that the pid value has the first process 1841
That is, the second shell opens inside the first shell, and the child shell or sub-shell is the same as the first shell
And since we got ps in the second shell, you see that pid subshell ppid is the ps command

When a sub-shell is created, not all objects in the environment are loose
And this can be a problem when working with variables, which we'll cover in the Variables section.

A sub-shell can also create a sub-shell itself, which becomes a secondary sub-shell.
(It is possible to create several shells in each other, which interact with each other)
Note the example below

$ ps -f
501 1841 1840  0  11:50 pts/0 00:00:00 -bash
501 2532 1841  1  14:22 pts/0 00:00:00 ps -f
$ bash
$ bash
$ bash
$ ps --forest
PID    TTY    TIME     CMD
1841 pts/0 00:00:00 bash
2533 pts/0 00:00:00      \_ bash
2546 pts/0 00:00:00           \_ bash
2562 pts/0 00:00:00                \_ bash
2576 pts/0 00:00:00                     \_ ps
Each of the bash commands you see is executed inside the previous command
Compare the output of two ps commands

Take a look at grammar lists

In one line you can list different commands so that they are executed one after the other, this is done by placing a semicolon (Wink between the commands
See the list of commands and outputs in their order in the example below
$ pwd ; ls ; cd /etc ; pwd ; cd ; pwd ; ls
Desktop Downloads Music Public Videos
Documents junk.dat Pictures Templates
Desktop Downloads Music Public Videos
Documents junk.dat Pictures Templates
Another format is like this
{ command ; }
The example above was a command list, to create a list of processes, just put the command list in parentheses
The difference between a command list and a process list is that the porocess list values are executed in a subshell
Note the example below, only one parenthesis was added to the command list, the output does not look different, but a big change has been made from the root
$ (pwd ; ls ; cd /etc ; pwd ; cd ; pwd ; ls)
Desktop Downloads Music Public Videos
Documents junk.dat Pictures Templates
Desktop Downloads Music Public Videos
Documents junk.dat Pictures Templates
To better see the change in the output of the above two examples, we use an environmental variable called BASH_SUBSHELL
If the commands are executed in a subshell, the value of this variable becomes 1, if they are not executed in a subshell, its value becomes 0.
(Each number related to the depth of the shell on the number of sub-shells, I will give an example earlier)
See the example above with this environmental variable:
$ pwd ; ls ; cd /etc ; pwd ; cd ; pwd ; ls ; echo $BASH_SUBSHELL
Desktop Downloads Music Public Videos
Documents junk.dat Pictures Templates
Desktop Downloads Music Public Videos
Documents junk.dat Pictures Templates
Here we display the value of $ variable with the echo command (number 0 last line)

That means the commands in the subshell are not executed

$ ( pwd ; ls ; cd /etc ; pwd ; cd ; pwd ; ls ; echo $BASH_SUBSHELL )
Desktop Downloads Music Public Videos
Documents junk.dat Pictures Templates
Desktop Downloads Music Public Videos
Documents junk.dat Pictures Templates
You can see that in this example we got output 1, because the process list ran sub-shell to run

You can also re-open the subshell in the process list, for example

$ ( pwd ; echo $BASH_SUBSHELL)
$ ( pwd ; (echo $BASH_SUBSHELL))
Note that the output for the subshell was the first command 1, like the previous examples
But the output of the second command was 2
Which says that this command is executed in the depth of two shell layers (second sub-shell, in the first sub-shell)

Use background mode

Background mode gives you the opportunity to wait when the shell is executing a command that takes time to do, and you can regain control of the shell at that moment.
To run a command in the background, just add & at the end of the & command

$ sleep 3000 &
[1] 2396
$ ps -f
501 2338 2337 0 10:13 pts/9 00:00:00 -bash
501 2396 2338 0 10:17 pts/9 00:00:00 sleep 3000
501 2397 2338 0 10:17 pts/9 00:00:00 ps -f
The above example executes the sleep command with a value of 3000 seconds (in background mode using & at the end of the command)
And because the command was executed in the background, the shell control was immediately returned to us and we were able to execute the ps command.
(If the previous command was not in the background, we would have to wait three thousand seconds to enter the next command)
In the output of the ps command we can see sleep running In addition to the ps command we can use the jobs command to see the background commands
$ jobs
[1] +   Running          sleep 3000 &
You can see that the jobs command shows the job number of each job plus the execution status and the name of the command and the value of its command

With the l-option, you can also see the pid of each command
jobs -l
[1] +   2399     running          sleep 3000 &
Whenever a job background is completed, the result will be announced on the page
[1] + Done                     sleep 3000 &
Put process lists in the background:

You know that process lists run in subshell, this way we can take the created subshell in the background
The following example illustrates both cases

In normal mode

$ (sleep 2 ; echo $BASH_SUBSHELL ; sleep 2)
In background mode
$ (sleep 2 ; echo $BASH_SUBSHELL ; sleep 2)&
[2] 2401
$ 1
[2]+ Done ( sleep 2; echo $BASH_SUBSHELL; sleep 2 )
In the background mode, the first line of the output is related to the moment of going to the background, the second and third lines are related to the output of the command and the announcement of the end of the job.

Do co-processing with the coproc command:

  The coproc command creates a subshell in the background, and executes the commands there
Note the interesting combination of co-processing with the process list in the example below

$ coproc ( sleep 10 ; sleep 20 )
[1] 2574
$ jobs
[1]+ Running coproc COPROC ( sleep 10; sleep 2 ) &
$ ps --forest
2483 pts/12 00:00:00 bash
2574 pts/12 00:00:00 \_ bash
2575 pts/12 00:00:00 | \_ sleep
2576 pts/12 00:00:00 \_ ps
Overview of built-in and external commands

External commands are commands that are outside the shell itself, usually in the following paths

/bin   /usr/bin   /sbin   /usr/sbin
For example, the ps command is an external command, you can find its storage with the which and type commands

$ which ps
$ type -a ps
ps is /bin/ps
$ ls -l /bin/ps
-rwxr-xr-x 1 root root 93232 Jan 6 18:32 /bin/ps
Whenever an external command is executed, a child process is created, for example.
$ ps -f
501 2743 2742 0 17:09 pts/9 00:00:00 -bash
501 2801 2743 0 17:16 pts/9 00:00:00 ps -f
The ps command itself is seen as one of the processes in the list where the ppid value is equal to the pid bash, which means that bash executes the ps print.

But built-in commands are commands that are part of the shell itself and do not run as a child process, like the cd and exit commands.

$ type cd
cd is a shell builtin
$ type exit
exit is a shell builtin
Unlike external commands, these commands are not seen anywhere outside the shell
Because no child process is required to execute built-in commands, these commands are faster than external commands.

But there are some commands that are a combination of these two types
For example, both echo and pwd commands are in this category

$ type -a echo
echo is a shell builtin
echo is /bin/echo
$ which echo
$ type -a pwd
pwd is a shell builtin
pwd is /bin/pwd
$ which pwd
Part One - Part 5

One of the influential factors in the shell environment are environmental variables, which are used by many programs and scripts, in this section you will become more familiar with them.
    Basically, environmental variables are used to store information about shells and work environments
    They also allow you to store data in memory so that it can be easily accessed by shell programs and scripts.
    There are two types of environmental variables in Bash Shell, which we will address

    global variables and local variables

    A look at global environmental variables:
    These types of variables are visible both inside the shell and within all of its sub-shells
    If the local type is only seen loose from within
    This uses the global type for applications that run subshells
    (Sub Shells Requesting Shell Print Information)
    When you enable SessionBash, the Linux system sets a number of global environmental variables, called system environment variables, which almost always use uppercase letters for their names to distinguish them from the variables defined by the user.
    To see the list of global environmental variables, we use the env and printenv commands

$ printenv

In the example above, I just gave you part of the output of the command
    Not only will some of the global environmental variables be set for you when you log in, but the type of login can be decisive in your choice.

    With the printenv command
    You can see the value of each of them, if of course by order
    env is not possible

$ printenv HOME
    $ env HOME
    env: HOME: No such file or directory
Of course, you can also do this with the echo command, which must use the $ sign before the variable name.
$ echo $HOME
It is important to know that using the $ sign before a variable name is not only to see the values of the variable, but also allows you to use the variable as a parameter of a command.

    Note the following example
$ ls $HOME
    Desktop    Downloads  Music     Public     test.sh
    Documents  junk.dat   Pictures  Templates  Videos
    $ ls /home/Backdoor
    Desktop    Downloads  Music     Public     test.sh
    Documents  junk.dat   Pictures  Templates  Videos
We said above that these variables can also be seen from within the subshell

    Note the following example

$ bash
    $ ps -f
    UID        PID  PPID  C STIME TTY          TIME CMD
    501       2017  2016  0 16:00 pts/0    00:00:00 -bash
    501       2082  2017  0 16:08 pts/0    00:00:00 bash
    501       2095  2082  0 16:08 pts/0    00:00:00 ps -f
    $ echo $HOME
    $ exit
Let's look at local environmental variables
    As their name implies, these variables can only be read from within the process by which they are defined.
    Although they are local, their global types are just as important. In fact, the Linux system defined this type of variable by default.
    However, you can define your own variables

The set command displays a list of all the variables for a definition process, including global, local, and user-defined, in the example below.

$ set
How to define user-defined variables
    After running the shell, you are allowed to define your own variables
    To define a variable, put the selected name together with the = sign and the value of the variable, without any spaces.
Note the following example
$ my_variable=Hello
    $ echo $my_variable

If there is a process gap, it becomes problematic, such as:
$ my_variable = "Hello World"
    —bash: my_variable: command not found
If you want to set the value of the variable to a string that also contains a space, you must put the string between single or double quotation marks, for example:
$ my_variable=Hello World
—bash: World: command not found
$ my_variable="Hello World"
$ echo $my_variable
Hello World
Without quotation marks, Shell thought the word was empty after the next sentence
    Note that the variable we defined, unlike the previous examples, is in lower case, because system variables are defined in uppercase. Whenever you want to define a variable in uppercase, you have to be careful about the similarity.

    When you define a local variable that can be accessed anywhere within your shell process, the problem arises when a sub shell becomes run.
    Consider the following example
$ my_variable="Hello World"
    $ bash
    $ echo $my_variable
    $ exit
    $ echo $my_variable
    Hello World
As you can see, the variable defined in the shell shell was not accessible from within the shell shell

    The same is true in the opposite case of this example, the following example:
$ echo $my_child_variable
    $ bash
    $ my_child_variable="Hello Little World"
    $ echo $my_child_variable
    Hello Little World
    $ exit
    $ echo $my_child_variable
You see that the output value of the blank line is not the value of the variable, because there is no such variable at this level

    How to define global environmental variables
    These variables, unlike the previous type, can be seen from inside any sub-shell that has its roots in the main shell.
    To create this type of variable you must first create a local variable and then export it to the global environment.

    This is done using the export command and the variable name without the $ sign, for example:
$ my_variable="I am Global now"
    $ export my_variable
    $ echo $my_variable
    I am Global now
    $ bash
    $ echo $my_variable
    I am Global now
    $ exit
    $ echo $my_variable
    I am Global now
Note that changing the value of a global variable defined in the shell print is not possible from within the sub-shell, see the example below
$ export my_variable
    $ echo $my_variable
    I am Global now
    $ bash
    $ echo $my_variable
    I am Global now
    $ my_variable="Null"
    $ echo $my_variable
    $ exit
    $ echo $my_variable
    I am Global now
According to this example, you can see that commands are passed from top to bottom, not the other way around
    Sub Shell could only define a variable with that name inside it
        Exporting follows the same principle, a variable is exported from above that is accessible from below, not the other way around, see the example below
$ my_variable="I am Global now"
    $ export my_variable
    $ echo $my_variable
    I am Global now
    $ bash
    $ echo $my_variable
    I am Global now
    $ my_variable="Null"
    $ export my_variable
    $ echo $my_variable
    $ exit

    $ echo $my_variable
    I am Global now
To delete variables, you must also use the unset command and the variable name without the $ sign
$ echo $my_variable
    I am Global now
    $ unset my_variable
    $ echo $my_variable
You can see that the output of the line is blank
    Of course, according to the principle I described, the sub-shell can not be changed in the shell print
    See the example below
$ my_variable="I am Global now"
    $ export my_variable
    $ echo $my_variable
    I am Global now
    $ bash
    $ echo $my_variable
    I am Global now
    $ unset my_variable
    $ echo $my_variable
    $ exit
    $ echo $my_variable
    I am Global now
You see, it just disappeared in the sub-shell

    Default loose environmental variables:

    Shell Bash sets certain variables by default to define the system environment
    Which can be useful for us, in the list below you can see the variables that Bash provides
    A colon-separated list of directories used as a search path for the cd command
    The current user’s home directory
    A list of characters that separate fi elds used by the shell to split text strings
    The filename for the current user’s mailbox (The bash shell checks this fi le for new mail.)
    A colon-separated list of multiple filenames for the current user’s mailbox (The bash shell checks each file in this list for new mail.)
    The value of the last option argument processed by the getopt command
    The index value of the last option argument processed by the getopt command
    A colon-separated list of directories where the shell looks for commands
    The primary shell command line interface prompt string
    The secondary shell command line interface prompt string
In addition to the above variables, Bash herself defines a number of these variables by herself
    The full pathname to execute the current instance of the bash shell
    An associative array of currently set aliases
    A variable array that contains the number of parameters being passed to a subroutine or shell script
    A variable array that contains the parameters being passed to a subroutine or shell script
    An associative array of locations of commands the shell has executed
    The shell command currently being or about to be executed
    When set, each bash script attempts to execute a startup file defined by this variable before running
    The command(s) passed using the bash -c option
    A variable array containing the source code line number of the currently executing shell function
    A read-only variable array containing patterns and their sub-patterns for positive matches using the regular expression comparison operator
    A variable array containing the source code filename of the currently executing shell function
    The current nesting level of a subshell environment (The initial value is 0.)
    A variable array that contains the individual major and minor version numbers of the current instance of the bash shell
    The version number of the current instance of the bash shell
    If set to a valid file descriptor (0,1,2), trace output generated from the 'set -x' debugging option can be redirected. This is often used to separate trace output into a file.
    A list of bash shell options that are currently enabled
    Process ID of the current bash process
    Contains the terminal width of the terminal used for the current instance of the bash shell
    An index into the variable COMP_WORDS, which contains the
    current cursor position
    The current command line
    The index of the current cursor position relative to the beginning of the current command
    The final key used to invoke the current completion of a shell function
    An integer value representing the type of completion attempted
    that caused a completion shell function to be invoked
    The Readline library word separator characters for performing
    word completion

    An array variable that contains the individual words on the
    current command line
    An array variable that contains the possible completion codes
    generated by a shell function
    An array variable that holds an unnamed coprocess’ I/O fi le
    An array variable that contains the current contents of the directory
    Indicates the emacs shell buffer is executing and line editing is
    disabled, when set to 't'
    When set, executes the startup fi le defi ned before a bash shell
    script runs (It is used only when the bash shell has been invoked
    in POSIX mode.)
    The numeric effective user ID of the current user
    The default editor used by the fc command

    A colon-separated list of suffi xes to ignore when performing fi le
    name completion
    The name of the currently executing shell function
    Sets the maximum allowed function nesting level, when set to a
    number greater than zero (If it is exceeded, the current command
    A colon-separated list of patterns defi ning the set of fi lenames
    to be ignored by fi le name expansion
    A variable array containing the list of groups of which the current
    user is a member
    Up to three characters, which control history expansion
    The history number of the current command
    Controls what commands are entered in the shell history list
    The name of the fi le in which to save the shell history list (.bash_history by default)
    The maximum number of lines to save in the history fi le

    Used as a formatting string to print each command’s timestamp
    in bash history, if set and not null
    A colon-separated list of patterns used to decide which com-
    mands are ignored for the history fi le
    The maximum number of commands stored in the history fi le
    Contains the name of the fi le that should be read when the shell
    needs to complete a hostname
    The name of the current host
    A string describing the machine the bash shell is running on
    The number of consecutive EOF characters the shell must
    receive before exiting (If this value doesn’t exist, the default is 1.)
    The name of the Readline initialization fi le (The default is.inputrc.)
    The locale category for the shell
    Overrides the LANG variable, defi ning a locale category

    Sets the collation order used when sorting string values
    Determines the interpretation of characters used in fi lename
    expansion and pattern matching
    Determines the locale setting used when interpreting doublequoted
    strings preceded by a dollar sign
    Determines the locale setting used when formatting numbers
    The line number in a script currently executing
    Defi nes the number of lines available on the terminal
    A string defi ning the system type in cpu-company-system format
    An array variable that holds read-in text from the mapfile com-
    mand when no array variable name is given
    How often (in seconds) the shell should check for new mail (The
    default is 60.)
    The previous working directory used in the shell

    If set to 1, the bash shell displays errors generated by the
    getopts command.
    A string defi ning the operating system the shell is running on
    A variable array containing a list of exit status values from the
    processes in the foreground process
    If set, bash starts in POSIX mode.
    The process ID (PID) of the bash shell’s parent process
    If set, the command to execute before displaying the primary
    An integer used to indicate the number of trailing directory
    names to display when using the \w and \W prompt string
    escapes (The directory names removed are replaced with one
    set of ellipses.)
    The prompt to use for the select command
    The prompt displayed before the command line is echoed if the

    bash -x parameter is used
    The current working directory
    Returns a random number between 0 and 32767 (Assigning a
    value to this variable seeds the pseudo-random number
    Readline buffer contents when using bind -x command
    Readline buffer content insertion point’s current position when
    using bind -x command
    The default variable for the read command
    The number of seconds since the shell was started (Assigning a
    value resets the timer to the value.)
    The full pathname to the bash shell
    A colon-separated list of enabled bash shell options
    Indicates the shell level, incremented by one each time a new
    bash shell is started

    A format specifying how the shell displays time values
    The value of how long (in seconds) the select and read com-
    mands should wait for input (The default of zero indicates to wait
    indefi nitely.)
    Directory name where the bash shell creates temporary fi les for
    its use
    The numeric real user ID of the current user
Reply 1
Part One - Part Six
    Linux uses location variables for a variety of purposes, you now know how to modify them, or create your own variables
    When you run a shell with Login, Bash checks several files by default
    These files are called startup files or environmental files
    The startup files that Bash checks on depend on the type of execution itself
    You can use a loose bash in three ways
    Default loose when logging in
    As an interactive shell that is considered a sub shell
    As a non-interactive shell for executing scripts
    Using any of the above methods, we specify the startup files we want
    The default shell when logging in deals with the following five startup files
The / etc / profile startup file is the default default file
    All system users run this file when logging in
    Need to know some Linux from
    pluggable authentication modules = PAM
    Are used, in which case the pam file process is executed before the shell is run, which causes a change in the default state of startups.

    You can see an example of the contents of this file in the box below

# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
    # and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).
    if [ "$PS1" ]; then
    if [ "$BASH" ] && [ "$BASH" != "/bin/sh" ]; then
    # The file bash.bashrc already sets the default PS1.
    # PS1='\h:\w\$ '
    if [ -f /etc/bash.bashrc ]; then
    . /etc/bash.bashrc
    if [ "`id -u`" -eq 0 ]; then
    PS1='# '

    PS1='$ '
    # The default umask is now handled by pam_umask.
    # See pam_umask(8) and /etc/login.defs.
    if [ -d /etc/profile.d ]; then
    for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
    . $i
    unset i
Each type of Linux applies different settings to this file
    For example, in this example, a file named /etc/bash.bashrc. It contains a list of situational variables

    Note that in the example below of the / etc / profile file, which belongs to CentOS distribution, there is no reference to a file named /etc/bash.bashrc

# /etc/profile
    # System wide environment and startup programs, for login setup
    # Functions and aliases go in /etc/bashrc
    # It's NOT a good idea to change this file unless you know what you
    # are doing. It's much better to create a custom.sh shell script in
    # /etc/profile.d/ to make custom changes to your environment, to
    # prevent the need for merging in future updates.
    pathmunge () {
    case ":${PATH}:" in
    if [ "$2" = "after" ] ; then
    }if [ -x /usr/bin/id ]; then

    if [ -z "$EUID" ]; then
    # ksh workaround
    EUID=`id -u`
    UID=`id -ru`
    USER="`id -un`"
    # Path manipulation
    if [ "$EUID" = "0" ]; then
    pathmunge /sbin
    pathmunge /usr/sbin
    pathmunge /usr/local/sbin
    pathmunge /usr/local/sbin after
    pathmunge /usr/sbin after
    pathmunge /sbin after
    HOSTNAME=`/bin/hostname 2>/dev/null`
    if [ "$HISTCONTROL" = "ignorespace" ] ; then
    export HISTCONTROL=ignoreboth

    export HISTCONTROL=ignoredups
    # By default, we want umask to get set. This sets it for login shell
    # Current threshold for system reserved uid/gids is 200
    # You could check uidgid reservation validity in
    # /usr/share/doc/setup-*/uidgid file
    if [ $UID -gt 199 ] && [ "`id -gn`" = "`id -un`" ]; then
    umask 002
    umask 022
    for i in /etc/profile.d/*.sh ; do
    if [ -r "$i" ]; then
    if [ "${-#*i}" != "$-" ]; then
    . "$i"
    . "$i" >/dev/null 2>&1
    unset i
    unset -f pathmunge
Of the rest of the startup files, most Linux use only one or two of them
Note that all four files start with a dot, which causes them to be hidden
    Because these files are in the directory of each user, each user can only modify his own files and add his own variables, so that they are active for each session he runs.

    Arrays :
    The interesting thing about environmental variables is that they can also be used as representations
    An array is a variable that can hold several values
    To create multiple values for a variable (convert to representation) just put them in parentheses and separate them with a space.

    $ mytest=(one two three four five)
The method of viewing the values of the presentations is different from the variables

    You can not display the value of the presentation with the method of variables
$ echo $mytest
Only the first value of the presentation was displayed

    To see the desired part of the presentation, we follow the following method
$ echo ${mytest[2]}
Because the presentation values start at zero, the place number becomes the third value2

    We use * to see all the values of the presentation
$ echo ${mytest[*]}
    one two three four five
You can even change just the amount you want
$ mytest[2]=seven
    $ echo ${mytest[*]}
    one two seven four five
You can see that the value of position number 2 changed to seven

    You can even delete the desired value using the unset command

$ unset mytest[2]
    $ echo ${mytest[*]}
    one two four five
    $ echo ${mytest[2]}
    $ echo ${mytest[3]}
If you are careful, you will notice that the value of position number 2 has been deleted and has not changed itself

    You can delete the entire presentation as shown below

$ unset mytest
    $ echo ${mytest[*]}
End of the sixth part of part one

Users browsing this thread: 1 Guest(s)