- Открытие терминала
- sudo – Super User Do
- Setting up your Pi
- Navigating the filesystem
- pwd – Print working directory
- ls – List the contents of a directory
- cd – Change directory
- Working with files
- cat – Print files to the terminal
- Less – Print Files on Terminal
- grep – Search inside a file
- nano
- htop – Display system processes
- free – Show amount of free and used RAM
- dmesg – Monitor kernel events , and with dmesg we can see what’s going on behind the scenes. Useful for debugging device issues.
- Manage Files
- mv – Move / rename file
- rm – Delete File
- cp – Copy File
- mkdir – Create directory
- Installing software
- apt – Installation and Management software
- ping – Check we’re connected
- hostname – Get the IP address of your Raspberry Pi
- Curl – Network transfer
- Time savers
- history
- grep story
- CTRL + R search
- Tab Completion
- Arrow keys
- alias
Most people run Linux on Raspberry Pi и его “официальная” операционная система – это версия Debian под названием Raspbian, которая была изменена только для Pi. С точки зрения обычного пользователя, пользовательский интерфейс Raspbian desktop по умолчанию похож на Windows, с главным меню и системным треем на рабочем столе, а также значками для обычных приложений.
Однако, как и все формы Linux, Raspbian имеет мощный интерфейс командной строки, который дает вам гораздо больше контроля над компьютером, чем вы можете получить с помощью графического интерфейса. И многие важные задачи либо проще, либо возможны только с помощью команд. Вот почему ниже мы перечислили наиболее важные команды для навигации по файловой системе, установки программного обеспечения, редактирования файлов и мониторинга производительности.
Открытие терминала
Чтобы открыть терминал из графического интерфейса Windows, либо щелкните значок терминала (он выглядит как крошечный монитор), либо нажмите CTRL + ALT + T. После открытия вы увидите черный экран с мигающей подсказкой. Если вы подключаетесь к своему Pi через SSH или вы уже загрузились в командной строке, вам не нужно открывать терминал, потому что вы уже там.
pi@raspberrypi:~ $
Это приглашение сообщает нам, что мы вошли в систему. в качестве пользователя по имени pi и что наша машина называется raspberry pi. $ относится к нашим разрешениям, поскольку у нас есть разрешение редактировать любой файл или папку в нашем домашнем каталоге, который в данном случае является /home/pi/.
В нашем домашнем каталоге мы можем хранить наши работы, проекты, фотографии и т.д. Но мы не можем нанести вред базовой файловой системе, поскольку у нас нет на это разрешения. Чтобы внести общесистемные изменения, нам нужно либо быть пользователем с именем “root”, который имеет аналогичные полномочия администратора в Windows, либо нам нужно использовать sudo (см. Ниже), чтобы временно предоставить нам дополнительные разрешения. В этом руководстве мы рассмотрим это и многое другое.
Итак, давайте начнем наше приключение с тестирования нескольких команд и узнаем больше о том, как работает наш Raspberry Pi.
sudo – Super User Do
По умолчанию Raspbian, как и все формы Linux, не дает вам привилегий администратора, необходимых для выполнения некоторых основных задач, таких как установка программного обеспечения. Однако, предваряя любую команду словом “sudo”, вы можете получить права администратора для этого выполнения. Чтобы использовать “sudo”, вы должны быть в группе разрешений “subdoers”, но хорошей новостью является то, что пользователь Raspberry Pi по умолчанию уже находится в этой группе.
For example, to upgrade your operating system, you would type:
sudo apt upgrade
Setting up your Pi
Would you like to change your password, enable VNC, overclock your Raspberry Pi, or set up a Wi-Fi network from the terminal, the easiest way is to use the configuration tool. To run it, just type:
sudo raspi-config
Navigating the filesystem
Navigating the filesystem is what we take for granted in the GUI environment. But with the help of the terminal, we can do everything, and with great speed and accuracy. We just need to know the right commands. If you don’t have permission to perform any of these actions on a particular file or directory, you may be allowed to prefix the command with sudo.
pwd – Print working directory
This command will show the full path to the directory we are in, for example /home/pi/.
pwd
ls – List the contents of a directory
This command is used to list the contents of a directory.
List the files in the current directory.
ls
List files in another directory, such as /var/log:
ls /var/log
See hidden files and directories in a long list with more information.
ls -lha
List all files of a particular type, such as Python .py files.
ls *py
cd – Change directory
With this command we can move around the file system. For example, to change from our home directory to Downloads
cd Downloads
Move to a directory on another part of the file system, such as /var/log.
cd /var/log
Go back to the previous directory we were in.
cd -
Go back to our home directory.
cd ~
Working with files
Sometimes we need to look inside a file, look for a specific command, error or bug, and with these commands we can do all this from the terminal.
cat – Print files to the terminal
Print the contents of the file on the terminal, for example a Python file.
cat test.py
Print the contents of the file to the terminal with line numbers.
cat -n test.py
Less – Print Files on Terminal
This command will print the contents of the file section by section and we can scroll through the file with the arrow keys, Page Up / Down and Home / End.
less than /var/log/syslog
grep – Search inside a file
To search inside a file for a specific word/section of text. Commonly used with log files when looking for problems. In this example, we use lscpu to print the processor information that is piped | in gre p, which we tell it to look for “MHz”.
lscpu | grep "MHz"
Edit File
For when you need to quickly edit a configuration file, Python code, or just write a to-do list.
nano
Nano is the easiest command line editor for beginners.
Create a new file like newfile.txt .
nano newfile.txt
Edit an existing file like test.py .
nano test.py
Within nano we navigate using the arrow keys , and it works just like a normal text editor.
Save your work.
CTRL + Ok Confirm the file name, press Enter
Quit nano.
CTRL + X
System resources and management
Managing our operating system and checking system resources is a standard practice in the terminal. Here we will show some commands to help you get started.
htop – Display system processes
Show current CPU load, RAM usage and running system processes. Installed by default on Raspbian. Useful for closing unresponsive applications.
htop
free – Show amount of free and used RAM
This command will tell us how much RAM is being used and what is free for applications. Using the -m option, we can set values in MB.
free -m
dmesg – Monitor kernel events , and with dmesg we can see what’s going on behind the scenes. Useful for debugging device issues.
dmesg
Manage Files
Moving, deleting, copying, and creating new files and directories are some of the most basic actions actions that we need to perform. From the terminal we can do this and more.
mv – Move / rename file
This command offers two functions. We can move a file from one location to another. For example, here we are moving test.py to the documents directory.
mv test.py Documents/
The command can also be used to rename a file or directory. Here we are renaming test.py to test2.py .
mv test.py test2.py
rm – Delete File
With this command we can delete files and directories. In this example, we are deleting the file test.py .
rm test.py
cp – Copy File
To copy a file like test.py to our Documents directory.
test cp.py Documents/
To copy a directory like /home/pi/test2 to /home/pi/ Documents/ we need to use the -r option to copy all the contents.
cp -r test2/ Documents/
mkdir – Create directory
Create a new directory to store your work. For example, let’s create a directory named Work in our home directory.
mkdir Work
Installing software
As on any computer, we need to make sure our software is running today, and on our Raspberry Pi, the tool for that is called apt.
apt – Installation and Management software
Apt, an advanced packaging tool. Linux App Store. To use apt, we will need to use sudo as it will make changes to the operating system.
First, we update the list of installed software.
sudo apt update
We can then install a specific application, for example to install vlc.
sudo apt will install vlc
Or we can update all the software on our Raspberry Pi. Note that we are passing the -y option to this command to automatically agree to install each package. But this is optional.
sudo apt upgrade -y
Network and Internet
Checking that your Raspberry Pi is connected to the Internet is simple but important task. This allows us to debug our IoT projects and watch YouTube videos.
ping – Check we’re connected
The ping command is used to making sure our Raspberry Pi is connected to the internet/home network.
We can ping a website.
ping google.com
Or to an IP address such as Google’s DNS server.
ping 8.8.8.8
Or we can send a ping to check connectivity internally to devices on our home network. This example assumes our IP address range is 192.168.1.1, but your range may differ.
ping 192.168.1.1
hostname – Get the IP address of your Raspberry Pi
The easiest way to find the IP address of our Raspberry Pi is to use the hostname with -I (capital i) which will show all IP addresses (Wi-Fi and Ethernet )
hostname -I
Curl – Network transfer
With this command we can transfer a file to our Raspberry Pi and back. For example, if we wanted to download an image from a website, we would use curl along with the -o option to create a file called image.jpg .
curl http://link-to-theimage.com /image.jpg - about image.jpg
The curl command is especially useful for downloading installation scripts to automatically install additional boards. But it should be used with care and check any code before using it.
Time savers
The Linux terminal has a lot of secrets and tricks to help you save time and become a keyboard ninja.
history
The history command will display the history of commands entered in the terminal. When used, it will output all commands at once as a long list.
history
There is a number at the beginning of each line in the list, and we can use that number to run that command again. But we have to prefix the number with an exclamation point.
!117
grep story
Using the “|” with the command history we can send the history output to grep where we can then look for specific commands. Here we are looking for all cases of “apt” in history.
history | grep “apt”
CTRL + R search
Using this, we can interactively search for a specific command in our command history. To start, we press CTRL + R together and then we start typing part of the command. For example, we just used the history | grep “apt” so now we can press CTRL+R and start typing history and search will find this command.
Tab Completion
Think of it as “autocomplete” for the terminal. The TAB key is located just above the Caps Lock key and we can use tab completion to execute long commands, directory listings. If we type the first few letters of a command like his and hit TAB, this will end the command to show the history.
But if we wanted to fill in a long directory path like /usr/lib/python3/ dist-packages, then we could start typing /usr/lib/ and then hit TAB to show us all the directories available in that path. We could then start typing python3 and by hitting TAB a few more times, the command would narrow down the options we could use.
Arrow keys
Another way to search your history is to use the up and down arrow keys. With these keys, we can navigate back and forth through our command history, and when the correct command is displayed, press Enter to run.
alias
With this command we can create shortcuts/short commands from much longer ones. For example here we create an alias called updater and use it to call two commands. The first one will update our list of installed software, and if that works successfully, denoted by “&&” to chain the commands together, it will run an update on our Raspberry Pi.
alias updater=”sudo apt update && sudo apt upgrade -y”
Now we can run our upgrade command by simply typing updater in the terminal. Note that once the Raspberry Pi is turned off, this alias is removed.