Bash

Contents
Introduction
SSH
Autocomplete
Arguments
View files
Edit text files
mkdir: create directories
Redirect output
Append data to file end
Default software
Aliases
*
exec bash: Restart terminal
Related topics

Introduction

$ in promt means, that you are using Bash % is for Zsh

~ before $ means you are in home

To execute the command you need to press Enter

The ls command shows the contents of the current directory

ls

docker Documents Music notes.txt Pictures python snap Templates yandex-tank Desktop docker-lab Downloads node_modules Public shell_scripts ssh-com Videos yarn.lock

By command cd you can change the directory

cd Documents

To return to the home directory, it is enough to run cd without parameters

To repeat the previous command, just press the up arrow

SSH

To connect to a remote computer by SSH execute

ssh username@hostname

ssh andrei@andrei-ubuntu

To close ssh session execute

exit

Learn more about working with SSH in Linux read the article « SSH Basics »

Automatic addition

When executing cd, it is not necessary to write the full name of the directory.

If you want to go to Documents from your home directory, just type Doc and press Tab.

If you just type D and press Tab, then Bash will not understand where you want to go - in Desktop, Documents or Downloads, so nothing will happen (a prompt will appear in Zsh immediately). But if you press Tab again - a hint will appear, namely a list of all directories, the name which starts with D

cd D

Desktop/ Documents/ Downloads/

To go to the parent directory execute

cd ..

To find out the full path to the current execute directory

pwd

Arguments

When you executed cd Documents, cd is a command, Documents is an argument.

To see hidden files in the execute ls directory -a

Where a means All

For hidden files, the first character in the name is a dot

ls -a

. .bashrc Desktop docker-lab .gnupg Music Public snap .sudo_as_admin_successful .Xauthority .. .bash_history .cache .docker Documents .local node_modules Pictures python .ssh Templates yandex-tank .bash_logout .config docker Downloads .mozilla notes.txt .profile shell_scripts ssh-com Videos yarn.lock

-a is a special kind of argument called an option.

Options add additional functionality to teams.

Options start with the - symbol

After -, you can list several options in a row

To see additional information about the files execute ls -l, l means long format

ls -l

total 96 drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Desktop drwxrwxr-x 3 andrei andrei 4096 syys 17 19:09 docker drwxrwxr-x 4 andrei andrei 4096 heinä 19 21:46 docker-lab drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Documents drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Downloads drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Music drwxr-xr-x 2 root root 4096 heinä 18 22:11 node_modules -rw-rw-r-- 1 andrei andrei 1 syys 19 21:40 notes.txt drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Pictures drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Public drwxrwxr-x 2 andrei andrei 4096 syys 19 12:54 python drwxrwxr-x 2 andrei andrei 4096 syys 19 22:01 shell_scripts drwxr-xr-x 3 andrei andrei 4096 syys 15 19:58 snap drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Templates drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Videos drwxrwxr-x 3 andrei andrei 4096 heinä 16 16:55 yandex-tank -rw-r--r-- 1 root root 86 heinä 18 22:11 yarn.lock

To find out what other options the ls execute command has

man ls

The result of this command will be a detailed description of all options. List long enough to move down the list, press the space bar to return to the top, press b

To perform a word search, type /the word. To go to for the next search result, press n

To close man click q

Read more about all ls options in the article «man ls»

To see additional information about files, including hidden ones and sort the output by the version of the change execute ls -lat

ls -lat

total 176 drwxr-xr-x 31 andrei andrei 4096 syys 20 10:20 . -rw------- 1 andrei andrei 34 syys 20 10:20 .lesshst -rw------- 1 andrei andrei 236 syys 20 10:16 .Xauthority -rw------- 1 andrei andrei 17546 syys 19 23:40 .bash_history drwxrwxr-x 2 andrei andrei 4096 syys 19 22:01 shell_scripts -rw-rw-r-- 1 andrei andrei 1 syys 19 21:40 notes.txt drwxrwxr-x 2 andrei andrei 4096 syys 19 12:54 python drwx------ 2 andrei andrei 4096 syys 17 19:19 .ssh drwxrwxr-x 3 andrei andrei 4096 syys 17 19:09 docker drwx------ 3 andrei andrei 4096 syys 15 20:04 .gnupg drwxr-xr-x 3 andrei andrei 4096 syys 15 19:58 snap drwxr-xr-x 15 andrei andrei 4096 syys 15 19:58 .cache drwxr-xr-x 12 andrei andrei 4096 syys 15 19:58 .config drwxrwxr-x 4 andrei andrei 4096 heinä 19 21:46 docker-lab drwx------ 2 andrei andrei 4096 heinä 18 23:06 .docker drwxr-xr-x 2 root root 4096 heinä 18 22:11 node_modules -rw-r--r-- 1 root root 86 heinä 18 22:11 yarn.lock drwxrwxr-x 3 andrei andrei 4096 heinä 16 16:55 yandex-tank drwxr-xr-x 4 andrei andrei 4096 heinä 16 15:08 .local -rw-r--r-- 1 andrei andrei 0 heinä 16 12:27 .sudo_as_admin_successful drwx------ 5 andrei andrei 4096 heinä 16 12:12 .mozilla drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Desktop drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Documents drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Downloads drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Music drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Pictures drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Public drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Templates drwxr-xr-x 2 andrei andrei 4096 heinä 16 12:11 Videos -rw-r--r-- 1 andrei andrei 220 heinä 16 11:53 .bash_logout -rw-r--r-- 1 andrei andrei 3771 heinä 16 11:53 .bashrc -rw-r--r-- 1 andrei andrei 807 heinä 16 11:53 .profile drwxr-xr-x 3 root root 4096 heinä 16 11:53 ..

Combine several commands into one

To see which terminal you are connected to execute

tty

/dev/pts/31

To make a listing of this file, you can copy the output and paste after ls

ls -l /dev/pts/31

crw--w---- 1 andrei tty 136, 31 мая 23 13:48 /dev/pts/31

To get the same result faster

ls -l $(tty)

crw--w---- 1 andrei tty 136, 31 мая 23 13:48 /dev/pts/31

Viewing files

To open the contents of a text file execute cat file_name or less file_name

cat textfile
lass book 1

cat will output the contents to console output. less will open the file in the entire window.

Navigating through a file opened with less is the same as navigating through man.

Whitespace down
b up
/ search
n next search result
q to close

If you are trying to open a binary file using less, you may get a warning

<

"file1" may be a binary file. See it anyway?

cat will open such a file without warning

To continue, press y. The result will most likely not please you - you will get a hard-to-read set of characters.

<C3>&NU_p<C6>x<E6><AC>^N<B4>E<EA>^B<D1>E^U<AB>^A3Fy<A3>^T^N<B5>7`^D<8E><F4><9F><8D>^M<E8>y<CD>^T6^A<DF>^T<83><8A>^F{џZ<8B><8C>p4S^G^TUs <C5>H@<DB><C3>}*d<C0>$<D4>Q^@Fq<83>S.:<81>\ƌp<E6><83>ӭ"<9F>j <C8><E9>I<92>/<BD>.i)hB \P(<A6>^B<D2>^Q<91><8A>)h^A*;<A9><96><DA><DA>K<86>Ve<8D>K<B0>Q<93><81><C9><C5>KU<F5>7X<B4>ۙ]<B6><A2>D<CC><C7>n<EC>^@9<E3><BD>RZ<8C><A5><E1>mv<D7><C4>~^^<B4><D7>4<F8><E7>^V<B7><91><89>a<F3>Sk<95>#<AE>3X<9A>7 <C4>^]'W<D4>m<EC>ml<B5>1<E7><DE><DC>X<89><9E><DB>^Q$Ђ]Y<B3><C7>B3<EA>^M`<FC>^P<D5><E3><87><U+009E>^Z<F0>Ǖ"<DD>[<E8><82>{<A0><E8><E0>Dw*<AA>30<FB><C4><EF><E3><FD><92>k^G<E1>t<B1>i<9E>%<BC><96>g<B9><B9>}O<C4>:<85><B4>6<C6>^V<D9>^P3K7<DA>^FG^K<B7>^K<92>y&<B4><E4>^]<8E><EB><C4>?^QtM <EF>T<B6><BE><B7><D4>7<E9>f<D7><ED>% ^E@<B8>m<B1><90>I^@<8C><F0>Ol^ZՓĶ<D1><E8>ڶ<AB>5<9D><EC>0<E9><86>a6<F8><86><E6><F2><F3><B9><94>^C<F3>^L^Lם<FC>a<F0>-<F7><88>|Ur<D6><C8>M<9E><A7>Ỉ.<C8>=g<B7>u<92><D8><FA>g{g覺<88><D6>h<FE>^M\I<AA>,<A9>wu<A4>I=<DA>^PIY%<8C><B3>.9<EE><C5>q<8A>9^U<84>t:^?<88>,<EF><FC>;a<AE>[Er<D6><FA><84>i-<AC>f<J<E1><97>p<F9>s<D7>^Y?AW4<8D>J<D7>T<B4>[<BB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B7><D0><E0><E3><E8>j<BF><85><BC>Ec<E2>(oe<B0>Y<D4>Y^Ke8<95>6<95><96>3<87>^<BC><E0><F7><AE>wB<B3><B9><BB><F8><96><FE>"<B6>i^SH_^O<C3>f<C1><F2>^D<B3><99>Y<86>A<EE><8A>1<9F><FA>hk<9F><F8>U<E2>ESCESCmCR<D3>C <C9>5֩<E2><AD>NH^@<88><FF>^@<A9>^D<BE><E2>F@^_(^Y$f<93><8A>Acд<BF>^QZj>#<D4><F4>(!<B9>^W^Zg<97><F6><96>h<F0><83>z<EE>\6y<E3>=<AB>d<F4><AF>1<B2><D5>WE<F8><8D><E3>k<B9>a<95><CD><CC><FA>]<AD><A8>򘇑<90><C7><D8>t ^E<81>'<D0>^Z<EE><FC>;<AD><DA>k<BA>y<BF><B1>Y<C4>"Y"<FD><F4>E^X<94>m<A4><80>{d^\^^<F4><9C>l<AE>I<A6>("<8A>*U<80>Lr^O<S<87>ZJ*<A2><80>u^T<99><A0>V<9C>ɈSH:<D0>h^T<80>O<D4>PzQ<C6>x<E3>ڑ<BD><E9>1<86>=M!<CE>^? <AD>)<C7>zi<F4>&<A4>^C<9A>(<FC>h<A0>

To close the window with these characters, try pressing q or enter the command reset

In order not to get into such a situation, you can check the file type before opening it. This can be done with the command file

file file1

file1: JPEG image data, JFIF standard 1.01, resolution (DPI), density 72x72, segment length 16, baseline, precision 8, 325x500, components 3

It turns out file1 is not a text but an image in JPEG format

You can try to open the image from the terminal with the command xdg-open, it's not a fact that it will work on your system, I have in Ubuntu 20.4 it turned out.

xdg-open file1

Editing text files

To edit a text file, you need to open it in one of the editors.

Most likely you already have either nano installed or vi

in nano, everything is pretty obvious about vi I advise you to read a separate article here

You can create a new file with the command touch

touch new_file

You can delete the file with the command rm

rm new_file

Create multiple files at once:

touch file1 file2 file3 file4

To create a file with spaces in the name, you need to put the name in quotation marks:

touch 'file with spaces in name'

You can create a new directory with the command mkdir

mkdir stands for Make Directory

mkdir new_folder

If you need to create nested directories, use the -p (parent) flag

mkdir -p city/district/street

To create a directory and go there immediately use

mkdir example && cd $_

To exit the current process, press CTRL + C

It is better not to use the following characters for file and folder names:

' " ` { } ( ) < > [ ] ! ? & ] : ; \ ^ $ @ ~ * #

Try opening the file with cat -vet

cat -vet somefile

You can see that there is $ at the end of the line, as well as the encoding of Cyrillic characters.

Redirecting output

The output can be redirected to a file using > or >>

> will delete the previous entries from the file

If you execute the redirect twice to the same file. Only the last one will remain

echo "Great laptops here"> log.txt
echo "Books with delivery in Russia here" > log.txt
vi log.txt

Books with delivery in Russia here

As you can see, the entry about laptops has not been preserved

How to add an entry to the end of a Bash file

To not overwrite and add a new line, you need to use >>

echo "Great laptops here" >> log.txt
echo "Books with delivery in Russia here" >> log.txt
vi log.txt

Great laptops here
Books with delivery in Russia here

The result of the command can be sent to another command.

If you are listing a directory with a large number of files with the ls command, for example ls/usr/bin the result won't fit on one screen.

It may be convenient to immediately forward this output to less

ls /usr/bin | less

To find the lines in the file with the mention of the desired word, use the command grep

Let's say you have a list of site partners aredel.com which is called partners.txt .

If you run

less partners.txt

The list will be very long

Авиасейлз Travel
Booking.com Hotels
Hotellook Hotels
TopBicycle.ru Bicycles
Велодрайв Bicycles
HeiHei.ru Travel
Xiaomi Android
Samsung Android
Book24 Books
GeekBrains Education
Нетология Education
SkillBox Education
Pluralsight Education
СовКомСтрахование Insurance
Полис 812 Insurance
Полис 812 Insurance
Vivo Android
Reg.ru Hosting

After the name comes the category to which the partner belongs.

Let's say you want to find all the partners of the Android category

grep Android partners.txt

Xiaomi Android
Samsung Android
Vivo Android

This list can be sorted alphabetically and saved in file android_partners.txt

grep Android partners.txt | sort > android_partnets.txt
cat android_partners.txt

Samsung Android
Vivo Android
Xiaomi Android

Let's calculate how many partners in the Education category are in this list.

cut -f 2 partners.txt | grep Education | wc -l

4

cut -f 2 leaves only the second column

grep Education leaves only Education

wc -l counts lines (word count -lines)

Indeed, there are four platforms in the education category GeekBrains, Нетология, SkillBox и Pluralsight

PATH

Check PATH

echo $PATH

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

Add the new_bin directory to PATH

export PATH=$PATH~/new_bin

Default programs

Set nano as the default editor with the command

export EDITOR=nano

To make this choice permanent, you need to make the appropriate entry in .profile (bash) или .zshenv (zsh)

You can also register there export PATH=$PATH~/new_bin

export EDITOR=nano export PATH=$PATH~/new_bin

Aliases

If you never use the ls command, but often run ls -a you might have thought - is it possible to somehow configure ls so that it always did lsa

It's not difficult to do this, and such renaming is called aliases. With their you can use it not only to redefine existing ones, but also to invent brand new commands.

export EDITOR=nano export PATH=$PATH~/new_bin alias ls="ls -la"

Получить список уже существующих alias можно командой

alias

alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"' alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias l='ls -CF' alias la='ls -A' alias ll='ls -alF' alias ls='ls --color=auto'

Если вы добавили alias в .profile и он не работает - попробуйте перезапустить терминал. Если не помогло пропишите в .bashrc . Если не помогло - создайте файл .bash_aliases и пропишите туда.

Тем кто пишет код на Python удобно делать алиас python - python3 чтобы пользоваться третьим Python и не указывать везде 3.

alias python="python3" alias pip="pip3"

*

Для работы с большим количеством файлов часто удобно использовать шаблоны.

Допустим вы хотите сделать листинг только .pdf файлов

ls *pdf

Найти все строки в файле filename в которых содержастья буквы a r g подряд.

grep *arg* filename

Перезагрузить терминал

To перезагрузить терминал не выходя из него, execute

exec bash

Related Articles
Bash
Bash Scripting
-eq -gt …: Операторы сравнения
if else: Условные операторы
Цикл while
date: Дата
Переход на новую строку
Арифметические операции
Передать файл или пароль по SFTP в Bash скрипте
Errors Bash
Banner Image

Search on this site

Subscribe to @aofeed channel for updates

Visit Channel

@aofeed

Feedbak and Questions in Telegram

@aofeedchat