Blog

April 3, 2020

Manjaro Linux, Bash & Touchscreen on a Raspberry PI 4 – 2

Read time: 10+  minutes – check the Table of Contents for overview. Hint – this full article is available as well as a PDF here.

Part 1. Part 3. Part 4.

BASH Shell (Terminal) Generic Commands – explanation, list of some basic commands, examples and hints, and finally simple C/C++ project compilation



BASH basics

Now that I have the IDEs and tools – before going on further we need this crucial milestone. Why? Because BASH or other similar shells are one of the most important user features of Linux, and they are super powerful!

BASH is the default shell on Manjaro Linux. It is also one of the most prominent shells for Linux. It is like the command prompt on Windows. The word Terminal is sometimes substituted with “the Console”, or “the command line”.

Other shells just FYI: Tcsh/Csh Shell (Enhanced C shell); Ksh – or Korn Shell; Zsh – The Z Shell; Fish – Friendly Interactive Shell.

FYI – the abbreviation CLI means Command Line Interface. And here is the full GNU BASH Manual. All GNU Manuals are here. For us at some point the GCC and Make programs are of interest.

How to start the BASH Terminal:

If you are in a GUI-less Linux distribution – this is probably the basic console which already runs. If you are in a distro with GUI like me – open the main menu with the mouse (or with the command button, on windows keyboard it is the windows button) and type terminal in the search. To avoid searching through the tree of programs each time right clicking on the search result gives a menu allowing you to add a Terminal Shortcut (icon) on the Desktop and / or the Panel (which is the taskbar normally at the bottom of your screen). Click it.

From the Keyboard in many distros the shortcut is (including Manjaro): Ctrl+Alt+T.

Now try your first command – type “ls” and press enter. It will show you the list of files in the current directory.

Further comes a list of basic commands (actually programs) I will use. Pay attention – each of them is a separate program, and it has almost always a good help. The help can be printed normally with writing some of these:

$ command –help

$ command -h   (some programs provide only the first option)

or sometimes:

$ command -?

Nota Bene – the commands given below work the same way in most Linux shells (as they are the same programs). The shells differences come from syntax for additional commands. And many copy the basic characteristics of BASH, adding some other enhanced features. But for basic work – you would rarely need those specific features.

Here it goes now: basic commands with short explanation and examples (21 of them):

sudo, ls, cd, ln, link, unlink, rm, cat, grep, ps, top, man, clear, find, cp, pwd, pidof, kill, killall, curl, whatis


sudo

One of the most important – it stands for “super user do!”, later “substitute user do”. For some programs / commands only the Linux system or the root user may start them. And your regular user, even if an administrator (the common case) – by default doesn’t have those rights. So – if some “program” cannot be executed by you – e.g. “pacman -Syu” requires root privileges – you will have to write it like this:

$ sudo pacman -Syu

as a result the system will ask you to enter the root password before being able to proceed.

“pacman -Syu” is the command to do full system update of all packages on your machine – compilers, libraries, drivers, etc.


ls and files permissions, chmod, chown

ls – to list all files/sub-directories in the current directory.

Option “-l” (minus EL small)   – list them one per line with some details (Long Listing format). Here is one of the lines when I list with “ls –l” in the Terminal:

drwxr-xr-x 2 my_user my_group 4096 Mar 12 16:24 Desktop

What does drwxr-xr-x mean? These are the files permissions. This is from the basics of the Linux Filesystem. The full description is:  drwxrwxrwx

If one of the letters is missing – then the given rights are missing

The first one is special and the full sequence is:

d – Directory, l – link, “-” – a file

r – User Read

w – User Write

x – User Execute

r – Group Read

w – Group Write

x – Group Execute

r – Others Read

w – Others Write

x – Others Execute

The R/W/X can be changed by an octal value: 4 for read, 2 for write, 1 for execute

The programs used to modify those:

chmod – change mode. Writing in the Terminal “chmod 760 example.txt” will set these rights: “-rwxrw—-“. Why? 7 is all bits up for User, 6 is read and write for group, 0 is no permissions for others. More in the link below.

chown – is the command we use to alter the ownership of the file. It’s used to change the user ownership and group ownership of the file. The format to use it is “sudo chown username.groupname filename”

chgrp – to change the group

More detailed information nicely described here and here:


cd

cd – Change Directory

If we list the current directory with “ls -l” and we have a directory MyDir somewhere in the listing then:

$ cd MyDir – will move us into this directory.

$ cd .. – go one directory up in the hierarchy

$ cd    – just like this – with no arguments – will switch back to your home directory.


ln

ln – the link create command. Detailed info: here.

There are two types of links in Linux/UNIX systems:

    Hard links – You can think a hard link as an additional name for an existing file. Hard links are associating two or more file names with the same inode. You can create one or more hard links for a single file. Hard links cannot be created for directories and files on a different filesystem or partition. inode is one node in the file system.

    Soft links – (or Symbolic Link) is something like a shortcut in Windows. It is an indirect pointer to a file or directory. Unlike a hard link, a symbolic link can point to a file or a directory on a different filesystem or partition.

By default, the ln command creates hard links. To create a symbolic link use, the -s (–symbolic) option.

Example for a symbolic link:

$ ln -s my_file.txt my_link.txt.


unlink

unlink – Removing links

$ unlink symlink_to_remove

Removing a symbolic link using the rm command is the same as when removing a file:

    $ rm symlink_to_remove


rm

rm – the remove command (aka delete 😉 ). More info: here.

Simply delete a file:

    $ rm filename

Delete without prompting for nonexistent files or arguments: with additional -f

$ rm -f filename

Delete with explicit Terminal printed feedback on what have been performed: with additional -v:

$ rm -v filename

Output: removed ‘filename’

Delete specific list of files:

$ rm filename1 filename2 filename3

You can use regular expressions to match multiple files. For example, to remove all .png files in the current directory, you would type:

$ rm *.png

To remove one or more empty directories use the -d option:

$ rm -d dirname

To remove non-empty directories and all the files within them recursively, use the -r (recursive) option:

$ rm -r dirname

The -i option tells rm to prompt the user for each given file before removing it:

$ rm -i filename1 filename2

-f – If the given directory or a file within the directory is write-protected, the rm command will prompt you to confirm the operation. To remove a directory without being prompted, use the -f option:

$ rm -rf dirname

The rm -rf command is very dangerous and should be used with extreme caution!.


cat

cat – the concatenate command: more info.

One of the most widely used commands in Linux. The name of the cat command comes from its functionality to concatenate files. It can read and concatenate files, writing their contents to the standard output. If no file is specified or if the input file name is specified as a single hyphen (-) it reads from the standard input.

    $ cat [OPTIONS] [FILE_NAMES]

OPTIONS – Use cat –help to view all available options.

FILE_NAMES – Zero or more file names.

$ cat /etc/issue  –  will print the current Linux distribution

$ cat file1.txt > file2.txt   –   copy the contents of file1.txt to file2.txt using the (>) operator. If the file2.txt file doesn’t exist, the command will create it. Otherwise, it will overwrite the file.

$ cat file1.txt >> file2.txt  –   Use the (>>) operator to append the contents of file1.txt to file2.txt

$ cat -n /etc/lsb-release     –   the -n will add lines numbers

$ cat file1.txt file2.txt > combinedfile.txt  –   will combine both files concatenated to the combinedfile.txt

$ cat file1.txt file2.txt >> file3.txt    –   To concatenate the contents of file1.txt and file2.txt and append the result to file3.txt to use the (>>) operator.

$ cat > file1.txt     –   simply create a new empty file (instead of opening nano, vi or vim editors).


grep – one of the most famous commands around!

More info here and GNU manual here.

GREP is an abbreviation from Global Regular Expression Print – it searches one or more input files for lines that match a given pattern and writes each matching line to standard output. If no files are specified, grep reads from the standard input, which is usually the output of another command.

Syntax:

$ grep [OPTIONS] PATTERN [FILE…]

Examples:

$ grep bash /etc/passwd   –   i.e. grep “STRING” “IN_THIS_FILE”

$ grep “I loook for this string with spaces”    file_to_check.txt

$ grep -v “nologin” /etc/passwd  –  To display the lines that do not match a pattern, use the -v ( or –invert-match) option.

To look into the output of a command for lines containing specific text e.g.:

$ ps -ef | grep bash

$ ps -ef  –   by itself will display all the running processes with their paths

The vertical line symbol “ | “ will make its output to be the input of the next command which is “grep bash“.

So this last one will search in this output only lines which contain the word “bash” and will output them to the terminal, so that we can see them.

—    —    —

To make combined search: first for “usr“, then for “lib“:

$ ps -ef | grep usr | grep lib

To look for two strings on the same line directly with grep (and not piping two grep calls) you can use the -E option, which asks grep to treat the searched pattern as a regular expression.

$ ps -ef | grep -E ‘usr.*lib’ some_file       – this looks for first usr, then lib

$ ps -ef | grep -E ‘lib.*usr’ some_file       – this looks for first lib, then usr

$ ps -ef | grep -E ‘usr.*lib|lib.*usr’ some_file      – this looks for first usr, then lib OR first lib, then usr

—    —    —

To look recursively into sub directories: use -r option – the next example will look for all occurrences of “manjaro.org” in all files of the /etc/ directory:

$ grep -r manjaro.org /etc/

If a report is returned that some files are not allowed for you to see – then simply add sudo in front of it and enter the password when prompted. This will really look into all files :).

$ sudo grep -r manjaro.org /etc/

-R (capital R) will follow also symbolic links! In my case (again with sudo) – it showed few more files for real 🙂

$ grep -R manjaro.org /etc/

Other options:

-n  –   show line numbers

-q (or –quiet) tells grep to run in quiet mode – not to display anything on the standard output. If a match is found, the command exits with status 0. This is useful when using grep in shell scripts where you want to check whether a file contains a string and perform a certain action depending on the result.

-c  –   to print a count of matches. Example that shows 5 matches on my machine:

$ ps -ef | grep  -c bash


ps

The command to list processes, some detailed info here.

In Linux, a running instance of a program is called process. Occasionally, when working on a Linux machine, you may need to find out what processes are currently running.

There are number of commands that you can use to find information about the running processes. ps, pstree, and top are the most commonly used.

$ ps aux

– The a option tells ps to display the processes of all users. Only the processes that are not associated with a terminal and processes of group leaders are not shown.

– u stands for a user-oriented format that provides detailed information about the processes.

– The x option instructs ps to list the processes out of the current terminal. Those are mainly processes that are started on boot time and running in the background.

$ ps -ef

– The -e option instructs ps to display all processes.

– The -f stands full-format listing, which provides detailed information about the processes.

– The command displays information in eight columns labeled UID, PID, PPID, C, STIME, TIME, and CMD.


top

Display Linux tasks, more info here.

When ran without arguments top will stay permanently on screen until you press q. The other way to stop it is via the regular Ctrl+c.

$ top -n 10   –   Exit Top Command after 10 repetitions (unless you press ‘q‘ or Ctrl+c before this).

Show the Absolute Path of Processes: Press ‘c‘  from the keyboard while top is running – it toggles this information. Press it second time – it switches back to regular mode.

More info on top here and here.


man – the show manual command

Despite that the regular option “—help” is many times detailed “man” will usually give you real manual explaining more on how the given program works, while the help is mostly for the basics and all parameters.

$ man cat – will display the Manual on cat

$ man ps – displays the manual of ps


clear – simply clear the BASH Terminal

This means that if we have several hundreds of lines in the backlog (results of commands like e.g. ls, top, ps or grep) – all of those will be deleted.


find

The find command in UNIX is a command line utility for walking a file hierarchy. It can be used to find files and directories and perform subsequent operations on them. It supports searching by file, folder, name, creation date, modification date, owner and permissions. By using the ‘-exec’ other UNIX commands can be executed on files or folders found.

Usage:

$ find OPTIONS STARTING/PATH expression

The options attribute will control the behavior and optimization method of the find process.

The starting/path attribute will define the top level directory where find begins filtering.

The expression attribute controls the tests that search the directory hierarchy to produce output.

Example:

$ find -O3 -L /var/www/ -name “*.html”

This command enables the maximum optimization level (-O3) and allows find to follow symbolic links (-L). find searches the entire directory tree beneath /var/www/ for files whose –name ends with .html.

More info here and here, man pages online: here.


cp – the copy command

    cp – to copy files.

$ cp somefile.txt newFileName.txt

$ cp /bin/somefile /home/SomeDirectory

$ cp file1 file2 file3  /SomeDirectory

Here are the options:

$ cp [OPTION] SOURCE DEST

$ cp [OPTION] SOURCE DIRECTORY

-a   archive files

-f   force copy by removing the destination file if needed

-i   interactive – ask before overwrite

-l   link files instead of copy

-L   follow symbolic links

-n   no file overwrite

-R   recursive copy (including hidden files)

-u   update – copy when source is newer than dest

-v   verbose – print informative messages

More information here, here and here.


pwd

PWD stands for Print Working Directory.

Options:

-P     if the current path holds also a symbolic link it will be changed with the real directory name

-L     forces pwd to use the Environmental variable PWD, even if it contains symbolic links


pidof

pidof – to understand the PID (process ID) of a process. You can see it also with top or ps.

If we execute “ps –aux” we will see all the processes in the system. systemd is the system and service manager used in many Linux distros, and in Manjaro as well. So this will give you it’s PID:

$ pidof systemd

If you start firefox with “firefox &” and then call

$ pidof firefox

you shall get several PIDs. Why? Because firefox runs several processes simultaneously. On my system it showed:

2134 2119 2075 1997

Some options:

  -s     Single shot – this instructs the program to only return one pid.

  -c     Only return process ids that are running with the same root directory.  This option is ignored for non-root users, as they will be unable to check the current root directory of processes they do not own.

  -x     Scripts too – this causes the program to also return process id’s of shells running the named scripts.

More information here.


kill and killall

kill “PID” – to stop the execution of a program. So if firefox has a PID 2134 this shall kill it:

$ kill 2134

You can also send a signal to a process:

Send a signal to process(es). Two famous are SIGSEGV (the segmentation fault) and SIGINT (the interrupt signal). More signals just for reference here.

-L   or   -l  (minus el both capital and small) will list for you all the signals you can send

— — — — —

killall – to end all instances of a running program. For our example with Firefox – it ran four processes. To Kill’em’all:

$ killall firefox

Some options (both long and short forms):

-e, –exact                           Require an exact match for very long names.  If a command name is longer than 15 characters, the full name may be unavailable (i.e.  it is swapped out).  In this case, killall will kill everything that matches within the first 15 characters.  With -e, such entries are skipped.  killall prints a message for each skipped entry if -v is specified in addition to -e,

-I, –ignore-case                               Do case insensitive process name match.

-g, –process-group         Kill the process group to which the process belongs.  The kill signal is only sent once per group, even if multiple processes belonging to the same process group were found.

-i, –interactive                                 Interactively ask for confirmation before killing.

-l, –list                                                 List all known signal names.

-q, –quiet                           Do not complain if no processes were killed.

-v, –verbose                      Report if the signal was successfully sent.

-w, –wait                            Wait for all killed processes to die.  killall checks once per second if any of the killed processes still exist and only returns if none are left.  Note that killall may wait forever if the signal was ignored, had no effect, or if the process stays in zombie state.


curl

curl – This is a super powerful program. The name comes from C-url, or Client url.

curl is a tool to transfer data from or to a server, using one of the supported protocols (DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET and TFTP). The command is designed to work without user interaction.

curl offers a busload of useful tricks like proxy support, user authentication, FTP upload, HTTP post, SSL connections, cookies, file transfer resume, Metalink, and more.

curl is used in command lines or scripts to transfer data. It is also used in cars, television sets, routers, printers, audio equipment, mobile phones, tablets, settop boxes, media players and is the internet transfer backbone for thousands of software applications affecting billions of humans daily.

The most common example:

$ curl www.google.com

This showed for me directly the html code of the google page. The next one save a file as yourfile.tar.gz:

$ curl -O http://yourdomain.com/yourfile.tar.gz

$ curl -o newfile.tar.gz http://yourdomain.com/yourfile.tar.gz

The last one saves it as newfile.tar.gz.

With the following command you will download info.html and about.html from http://yoursite.com and http://mysite.com, respectively, in one go.

$ curl -O http://yoursite.com/info.html -O http://mysite.com/about.html

The manual is quite big. Most of the examples above are coming from this site: https://www.tecmint.com/linux-curl-command-examples/. The official website (and I recommend checking it) is https://curl.haxx.se/. Another example page: here.


whatis

whatis – to ask one line brief description of some command –

$ whatis top                       – prints “display Linux processes”

$ whatis ls cp rm mv               – prints the one line definition of the four commands

To ask for anything which starts with ‘who’

$ whatis -w ‘who*’

To ask for anything which contains ‘bin’ in its name:

$ whatis -w ‘*bin*’

More information here.


whereis

whereis – to locate a program – the binary, the source (if available) and the manual page files for the given command

Example: type “whereis ping”. On my machine (shall be the same on most or all regular linux distributions) the terminal returned:

ping: /usr/bin/ping /usr/share/man/man8/ping.8.gz




Piping and redirection of commands in bash – crucial to understand how it shall be used and also one of the greatest powers of the shell.

What does this mean?

From this link:

Every program we run on the command line automatically has three data streams connected to it.

STDIN (0) – Standard input (data fed into the program)

STDOUT (1) – Standard output (data printed by the program, defaults to the terminal)

STDERR (2) – Standard error (for error messages, also defaults to the terminal)

The numbers in braces show the IDs of these three streams.

Piping and redirection is the means by which we may connect these streams between programs and files to direct data in interesting and useful ways.


Piping

Piping let you use the output of a program as the input of another one (more info here).

This is done with the special symbol vertical line “|“. So if we have :

command_1 parameters | command_2 parameters | command_3 parameters | command_4 parameters

these commands will be executed in the sequence 1,2,3 and 4. They will be one after the other. The output from each command will be the input for the next one. Finally in the terminal we will see the output of the last one. Examples were show already above:

$ ps -ef | grep usr | grep lib

First “ps -ef” gives a big list. This list is passed to “grep usr” – which results in shorter list. Then this list is passed to “grep lib” – which results in final list printed to the standard output of the Terminal.

This means we have a sequence of stdout_1 -> stdin_2 -> stdout_2 -> stdin_3 -> stdout_3 -> Terminal_Output

In any case – if an error occurs during the execution – it will be shown in the terminal. stderr is by default sent to the terminal.

Sometimes this may lead to complete exit from the chain of commands, other times – the error will be printed, but the programs will continue processing the chain.

If we want to pipe also the STDERR (it is with ID 2) the Bash reference manual says:

If ‘|&’ is used, command_1’s standard error, in addition to its standard output, is connected to command_2’s standard input through the pipe; it is shorthand for “2>&1 |”. This implicit redirection of the standard error to the standard output is performed after any redirections specified by the command.

Example: before going to it first let’s see the Redirection:


Redirection

Redirection is changing where the stdin, stdout or stderr goes. This is the input for an operation, the output from an operation, and eventually some error output.

Redirections are processed in the order they appear, from left to right (more info here).

This is done via the special symbol greater than “>”.  Bash Reference for redirections here.

Basic example: Searching for all files which contain the word “bash” in the /etc directory, recursively, and finally pointing out the results to a file:

$ grep -r bash /etc >results.txt

— — — — —

Some files give errors without sudo (regular user cannot read them), as we are never the root (in the common case). And as the results are going to a file – in the terminal we shall see only the errors.

So to transfer these errors to another file use the ID 2 of the stderr stream:

$ grep -r bash /etc >results1.txt 2>err2.txt

Using cat to display the given text file results will show the given listings.

— — — — —

To make the next experiment: let’s first navigate with “cd ..”, pwd, ls and so on to the /etc directory. It is full of stuff to search and to experiments with piping and redirections.

Two important points – don’t change things there without reading in advance (grep is safe of course – we only read and search)! In addition:

Note that the order of redirections is significant. For example, the command

$ ls > dirlist.txt 2>&1

directs both standard output (file descriptor 1) and standard error (file descriptor 2) to the file dirlist.txt, then simply states that STDERR from this command goes to STDOUT

while the command

$ ls 2>&1 > dirlist.txt

directs only the standard output to file dirlist.txt, because the standard error was first made a copy TO the standard output before the standard output was redirected to dirlist.txt.

In other words the first will put both results AND STDERR to the file dirlist.txt, while in the second way the dirlist.txt will contain only the STDOUT, without the STDERR (and the STDERR will go to the current terminal STDOUT, i.e. the &1).


Piping and Redirection together

We wanted to present how “|&” works. For this we will search for bash in the etc folder and transfer this to a result file:

$ grep -r bash /etc >results.txt

Again – this points the STDOUT to the file, while on the Terminal we only see the resulting errors from files, which we were not allowed to open and read due to user Permission denied.

Adding one more filter will show (in my case) some results in the text file and all Permission Denied messages on the Terminal:

$ grep -r bash /etc | grep home >results.txt

And if we add an ampersand like this:

$ grep -r bash /etc |& grep home >results.txt

the Permission Denied messages will be hidden in the pipe and not sent to the Terminal.


The other operators – < and >>

First the less than: “ <

This one is used to direct the contents of a file as an input to a program (or command) like here:

$ wc -l < barry.txt > myoutput.txt

wc is a Word Count program. Barry.txt is the input file. The minus el “-l” option means count the lines from this input. The myoutput.txt is where to print the result.

I have a text file results.txt with some lines, few of which include the word “matches” and I want to search for it with grep:

$ grep matches <results.txt

And I can easily append the results to some other file:

$ grep matches <results.txt >results1.txt

If you try to use the same file as input and output bash will complain ;).

And if I execute this given command 10 times results1.txt will always be with the same contents – each time completely overridden.

If I want to append contents to results1.txt I shall use the double bigger operator: “ >>

$ grep matches <results.txt >>results1.txt




Using Autocomplete in BASH, starting commands on the foreground and background, writing a simple script.


Autocomplete.

It is really helpful.

When typing in the Bash terminal: if we are e.g. in the current home directory, and it contains the subdirectory /myUser/Desktop/ :

When trying the cd command typing only “cd my”, and then pressing TAB on the keyboard – this will complete the word to my”User/”.

If we then type Des and press TAB again – this will complete the directory name to Des”ktop/”.

[myUser@myPc home]$ cd my                –   I press TAB here and the result is for me:

[myUser@myPc home]$ cd myUser/               –   I press TAB AGAIN and the result is for me:

[myUser@myPc home]$ cd myUser/Desktop

The other important point – all standard programs like ls, grep, cat, lsmem, hwinfo, umount, reboot, screenfetch and so on – they are put on a list of known commands. Even in my case the preinstalled firefox.

So if I want to use the long command screenfetch – what I would do is type “scree” and press TAB. This will autocomplete the word for me.

If I only type scr and press TAB twice – the BASH Terminal will show for me the possible options to complete – so adding only one more letter and pressing TAB will finally complete the word.

Here it is:

[myUser@myPc home]$ scr                –   I press TAB twice here and the result is for me:

screenfetch     script      scriptlive            scriptreplay

[myUser@myPc home]$ scre               –   I type ‘e‘ and press TAB AGAIN and the result is for me:

[myUser@myPc home]$ screenfetch


Execute a program / application

To execute a program – it shall be a file with rights to be executed. When listing in detail with ls –l the given file needs to be with execute permission for the current user and group. The file extension can be any (if there is such at all – in Linux regular programs don’t have file extensions). In Windows we need a .exe at the end of the file. Linux says – if your file can be executed as a program – it shall only have the corresponding file permission. If it doesn’t, and you know it is a valid program – change the permission with chmod (command mentioned earlier).

From BASH shell for known programs (which are in a BASH internal list) this is done via simply typing the name of the program and pressing Enter – like we did for ping, cd, ls, top, …. or firefox. This however will “block” the currently started terminal until the given program finishes or is terminated e.g. with Ctrl+c.

To background the process, so your terminal doesn’t sit there hung until you exit the application – append and ampersand “&” to the end of the command like here:

[myUser@myPc home]$ firefox &

[1] 3926

[myUser@myPc home]$

The 3926 is the new process PID.

Again – this is for the known programs which exist in the Interactive Autocomplete of the BASH shell database.

Now if we have a simple application, like HelloWorld (how to build one super easy – check the last chapter) in our directory home/myUser/Desktop/testProgram/ one has to type in front of it a dot and a slash like this:

[myUser@myPc testProgram]$ ./HelloWorld    – and then hit Enter 🙂

The dot and slash say to BASH: run this HelloWorld (and not another executable located somewhere else (e.g. usr/bin/firefox) in the file system). About the dot and slash you may check this link.

In the same manner as before an ampersand & at the end will start the program in background, keeping our Terminal free to get some new task from us.

If I’m not in the given directory – e.g. I’m in home – then I have to do:

[myUser@myPc home]$ ./myUser/Desktop/testProgram/HelloWorld

Reminderkilling a program – if by some reason we started a process with & on the background which we want to stop – if you don’t know the PID – use TOP or pidof. Find the PID (e.g. 3926) and call “kill 3926”. Sometimes kill or killall will require a sudo in front.

Regarding the BASH commands list – most of those programs are actually located in the /usr/bin directory. This list comes from the PATH environment variable.

Linux path environmental variable contains a list of directories in which the shell looks for executable programs every time you run a command or program. Use echo command to print your PATH variable:

$ echo $PATH

So – if you install new SW and it adds a binary to some of the directories listed in $PATH – upon next start of the Terminal it will also add it to the list of known commands. For custom commands – you can add your own directory e.g. with scripts and extend the $PATH with it. Then upon next terminal start it will be available. Of course the given file must be with execution rights. How to add a path to the $PATH list is described in chapter 5.8.


Writing a simple BASH script

What is a bash script? It is like batch files in Windows – a series of commands, saved in a text file, and then given to the terminal as a command. This results in Terminal opening the file, executing the commands and finally exiting. As we are in the bash terminal – the script shall apply strictly to the syntax rules of the BASH Shell.

If it outputs a result to the Terminal – then this will be printed to the STDOUT and we will see it. If inside there are piped commands – many of those will not be printed.

Let’s see an example:

With Sublime_Text I create a simple file which contains the following lines:

—    —    —    —    —    —    —    —    —    —    —    —    —

echo Trying some basic BASH shell script

ps -ef

ls -l

grep -r bash /etc 2>&1 >/home/myUser/results4.txt

—    —    —    —    —    —    —    —    —    —    —    —    —

I saved it under the name myScript.sh.

Then I go to the Terminal, and using chmod I apply the permissions for this script to be executed:

[myUser@myPc home]$ chmod 766 ./myUser/myScript

Further we write there again with the ./ in front:

[myUser@myPc home]$ ./myUser/myScript.sh

This is enough to execute the script and see the results printed on the Terminal.  That’s all.

For advanced usage – the scripts support variables, conditional execution of lines and many other options. Those may come in other articles. Check this link for few more basic examples for scripting.


The echo command – important specially about scripts

Simply put – echo returns to the terminal exactly what you have given to it as text.

Apart from some nice tutorials on the internet, if you want to display the help of echo – you are in trouble. Echo repeats what it is given to the current STDOUT. So the best way to see all its options is to call “man echo”.

The other way – typing the full path to it and writing:

[myUser@myPc home]$ /bin/echo –help

When is it useful? In bash scripts to print to stdout explicitly a variable, a conditional message, and any info you need when piping multiple commands and thus “hiding” the info from the Terminal. It supports also formatting of text with classical excape sequences like \\, \t, \r, \n…



More on multiple commands in BASH shell

Here follow some lists (like mine here) of basic linux commands:

https://www.pcsuggest.com/basic-linux-commands/

https://linoxide.com/linux-command/essential-linux-basic-commands/

https://linuxhint.com/top-25-linux-commands-with-examples/

https://www.addictivetips.com/ubuntu-linux-tips/basic-linux-terminal-commands/

https://www.ubuntupit.com/best-linux-commands-to-run-in-the-terminal/

https://www.puttygen.com/linux-commands

Otherwise – use any search machine (Google, DuckDuckGo) by typing e.g. for grep:

grep Linux command

You will get tens or even hundreds of good results. Many people like me make shorter or longer summaries, give examples. Finally you have the man command to display the full manual of the given program in the Terminal, or online full documentation of the given commands as they are 100% FOSS (Free and Open Source Software).




How to compile a simple C/C++ project

The next important steps is to try and compile a project (Hello World) written with whatever text editor.

This shall be easy some may say, and it is.

My source file is in C++ – with Sublime_Text I created a Hello.cpp in a New folder called Cpp_Projects/Hello.cpp.

In it I’ve entered the following simple C++ code:

—– —– —– —– —– —– —– —– —– —– —–

#include <iostream>

using namespace std;

int main (void) {

cout << “Hello World” << endl;

return 0;

}

—– —– —– —– —– —– —– —– —– —– —–

Then I went to the Terminal, to the given folder and for C++ I have entered on the terminal this single compile line:

$ g++ -o Hello Hello.cpp

For a C based project it is the same, but with calling gcc instead of g++.

This created for me the application Hello. When checking with ls -l I have now the execute permission.

With “./” in front I can call it and in the Terminal :

[myUser@myMachine Cpp_Projects]$ ./Hello

prints for me the notorious words “Hello World”.

Yes, it IS that simple :). Some more information you can find here.

Prev: Part 1. Next: Part 3.

Manjaro Linux on Raspberry Pi 4

Leave a Reply

Your email address will not be published. Required fields are marked *