Linux make build directory

Linux: How to Make a Directory Command

H ow do I make directory under Linux operating systems using the command prompt or bash shell?

You need to use the mkdir command to create new folders or directories under Linux operating systems. A directory (also known as folder in MS-Windows/macOS ) is nothing but a container for other directories and files. This page explains the basics of using the mkdir command on Linux.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements mkdir on Linux
Est. reading time 3 mintues

mkdir command Syntax

The mkdir command has the following syntax:
mkdir dirname
mkdir dirname1 dirname2
mkdir [option] dieNameHere
mkdir -p dir1/dir2/dir3

Examples

Let us see some commann useful examples.

How to create a new director

Open a terminal and then use the mkdir command to create empty directories. The following command would create a directory called foo:
$ mkdir foo
To list directories, enter:
$ ls
$ ls -l
The following command would create two directories within the current directory:
$ mkdir tom jerry
$ ls -l

How to create Directories in Linux

The -p option allows you to create parent directories as needed (if parent do not already exits). For example, you can create the following directory structure:
$ mkdir -p

/public_html/images/trip
Verify it:
ls -l

/public_html/
ls -l

/public_html/images/
ls -R -l

How to create directories in Linux with verbose option

Pass the -v as follows to display a message for each created directory:
mkdir -v dir1
ls -l

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Setting up permissions when creating a directory

To set directory mode (permission) pass the -m option as follows:
mkdir -m dirName
The -m option is same as giving permissions using the chmod command. For examples:
mkdir data
chmod 0700 data
We can do the same with a single command and save typing time at the command-line:
mkdir -v -m 0700 data
ls -ld data

Setting up SELinux context with mkdir on RHEL or CentOS

The syntax is follows to set up system_u:object_r:httpd_sys_content_t:s0 as SELinux context for foo dir:

How to Create a Directory in Linux with mkdir Command with SELinux

Sample mkdir demo command

Animated gif 01: mkdir in action under Linux / Unix like operating systems

Summing up

The mkdir command in Linux is used to make new directories as per your needs. We create a new directory in current directory or given path:
mkdir my-dir-name-here
ls -l
Also make directories recursively which is useful for creating nested dirs on Linux. For instance:
mkdir -p path/to/dir1/dir2

Getting help

Make sure you read the following man pages:
man mkdir
man ls
mkdir —help

Options summary

Option Description Example
-m ( —mode=MODE ) Set file mode (as in chmod command), not a=rwx – umask. mkdir -m 0644 sales
-p ( —parents ) No error if existing, make parent directories as needed. mkdir -p one/two/three
-v ( —verbose ) Print a message for each created directory. mkdir -v detla
-Z Set SELinux security context of each created directory to the default type. mkdir -Z dir1
—context[=CTX] Like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX. See above
—help Display this help and exit. mkdir —help
—version output version information and exit. mkdir —version

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Просто о make

Меня всегда привлекал минимализм. Идея о том, что одна вещь должна выполнять одну функцию, но при этом выполнять ее как можно лучше, вылилась в создание UNIX. И хотя UNIX давно уже нельзя назвать простой системой, да и минимализм в ней узреть не так то просто, ее можно считать наглядным примером количество- качественной трансформации множества простых и понятных вещей в одну весьма непростую и не прозрачную. В своем развитии make прошел примерно такой же путь: простота и ясность, с ростом масштабов, превратилась в жуткого монстра (вспомните свои ощущения, когда впервые открыли мэйкфайл).

Мое упорное игнорирование make в течении долгого времени, было обусловлено удобством используемых IDE, и нежеланием разбираться в этом ‘пережитке прошлого’ (по сути — ленью). Однако, все эти надоедливые кнопочки, менюшки ит.п. атрибуты всевозможных студий, заставили меня искать альтернативу тому методу работы, который я практиковал до сих пор. Нет, я не стал гуру make, но полученных мною знаний вполне достаточно для моих небольших проектов. Данная статья предназначена для тех, кто так же как и я еще совсем недавно, желают вырваться из уютного оконного рабства в аскетичный, но свободный мир шелла.

Make- основные сведения

make — утилита предназначенная для автоматизации преобразования файлов из одной формы в другую. Правила преобразования задаются в скрипте с именем Makefile, который должен находиться в корне рабочей директории проекта. Сам скрипт состоит из набора правил, которые в свою очередь описываются:

1) целями (то, что данное правило делает);
2) реквизитами (то, что необходимо для выполнения правила и получения целей);
3) командами (выполняющими данные преобразования).

В общем виде синтаксис makefile можно представить так:

То есть, правило make это ответы на три вопроса:

Несложно заметить что процессы трансляции и компиляции очень красиво ложатся на эту схему:

Простейший Makefile

Предположим, у нас имеется программа, состоящая всего из одного файла:

Для его компиляции достаточно очень простого мэйкфайла:

Данный Makefile состоит из одного правила, которое в свою очередь состоит из цели — «hello», реквизита — «main.c», и команды — «gcc -o hello main.c». Теперь, для компиляции достаточно дать команду make в рабочем каталоге. По умолчанию make станет выполнять самое первое правило, если цель выполнения не была явно указана при вызове:

Компиляция из множества исходников

Предположим, что у нас имеется программа, состоящая из 2 файлов:
main.c

Makefile, выполняющий компиляцию этой программы может выглядеть так:

Он вполне работоспособен, однако имеет один значительный недостаток: какой — раскроем далее.

Инкрементная компиляция

Представим, что наша программа состоит из десятка- другого исходных файлов. Мы вносим изменения в один из них, и хотим ее пересобрать. Использование подхода описанного в предыдущем примере приведет к тому, что все без исключения исходные файлы будут снова скомпилированы, что негативно скажется на времени перекомпиляции. Решение — разделить компиляцию на два этапа: этап трансляции и этап линковки.

Теперь, после изменения одного из исходных файлов, достаточно произвести его трансляцию и линковку всех объектных файлов. При этом мы пропускаем этап трансляции не затронутых изменениями реквизитов, что сокращает время компиляции в целом. Такой подход называется инкрементной компиляцией. Для ее поддержки make сопоставляет время изменения целей и их реквизитов (используя данные файловой системы), благодаря чему самостоятельно решает какие правила следует выполнить, а какие можно просто проигнорировать:

Попробуйте собрать этот проект. Для его сборки необходимо явно указать цель, т.е. дать команду make hello.
После- измените любой из исходных файлов и соберите его снова. Обратите внимание на то, что во время второй компиляции, транслироваться будет только измененный файл.

После запуска make попытается сразу получить цель hello, но для ее создания необходимы файлы main.o и hello.o, которых пока еще нет. Поэтому выполнение правила будет отложено и make станет искать правила, описывающие получение недостающих реквизитов. Как только все реквизиты будут получены, make вернется к выполнению отложенной цели. Отсюда следует, что make выполняет правила рекурсивно.

Фиктивные цели

На самом деле, в качестве make целей могут выступать не только реальные файлы. Все, кому приходилось собирать программы из исходных кодов должны быть знакомы с двумя стандартными в мире UNIX командами:

Командой make производят компиляцию программы, командой make install — установку. Такой подход весьма удобен, поскольку все необходимое для сборки и развертывания приложения в целевой системе включено в один файл (забудем на время о скрипте configure). Обратите внимание на то, что в первом случае мы не указываем цель, а во втором целью является вовсе не создание файла install, а процесс установки приложения в систему. Проделывать такие фокусы нам позволяют так называемые фиктивные (phony) цели. Вот краткий список стандартных целей:

  • all — является стандартной целью по умолчанию. При вызове make ее можно явно не указывать.
  • clean — очистить каталог от всех файлов полученных в результате компиляции.
  • install — произвести инсталляцию
  • uninstall — и деинсталляцию соответственно.

Для того чтобы make не искал файлы с такими именами, их следует определить в Makefile, при помощи директивы .PHONY. Далее показан пример Makefile с целями all, clean, install и uninstall:

Теперь мы можем собрать нашу программу, произвести ее инсталлцию/деинсталляцию, а так же очистить рабочий каталог, используя для этого стандартные make цели.

Обратите внимание на то, что в цели all не указаны команды; все что ей нужно — получить реквизит hello. Зная о рекурсивной природе make, не сложно предположить как будет работать этот скрипт. Так же следует обратить особое внимание на то, что если файл hello уже имеется (остался после предыдущей компиляции) и его реквизиты не были изменены, то команда make ничего не станет пересобирать. Это классические грабли make. Так например, изменив заголовочный файл, случайно не включенный в список реквизитов, можно получить долгие часы головной боли. Поэтому, чтобы гарантированно полностью пересобрать проект, нужно предварительно очистить рабочий каталог:

Для выполнения целей install/uninstall вам потребуются использовать sudo.

Переменные

Все те, кто знакомы с правилом DRY (Don’t repeat yourself), наверняка уже заметили неладное, а именно — наш Makefile содержит большое число повторяющихся фрагментов, что может привести к путанице при последующих попытках его расширить или изменить. В императивных языках для этих целей у нас имеются переменные и константы; make тоже располагает подобными средствами. Переменные в make представляют собой именованные строки и определяются очень просто:

Существует негласное правило, согласно которому следует именовать переменные в верхнем регистре, например:

Так мы определили список исходных файлов. Для использования значения переменной ее следует разименовать при помощи конструкции $( ); например так:

Ниже представлен мэйкфайл, использующий две переменные: TARGET — для определения имени целевой программы и PREFIX — для определения пути установки программы в систему.

Это уже посимпатичней. Думаю, теперь вышеприведенный пример для вас в особых комментариях не нуждается.

Автоматические переменные

Автоматические переменные предназначены для упрощения мейкфайлов, но на мой взгляд негативно сказываются на их читабельности. Как бы то ни было, я приведу здесь несколько наиболее часто используемых переменных, а что с ними делать (и делать ли вообще) решать вам:

Источник

How to make a folder in Linux or Unix

How to make a folder in Linux

The procedure is as follows:

  1. Open the terminal application in Linux
  2. The mkdir command is is used to create new directories or folders.
  3. Say you need to create a folder name dir1 in Linux, type: mkdir dir1

Let us see examples and other usage in details. The syntax is:

Now you know the syntax. Let us explore how to create new folders and directories on Linux or Unix-like system using the command line option.

How to create a new folder named foo in Unix

Open the Terminal app and type the following command:
mkdir foo
To see directory listing use the ls command:
ls
ls -l
You can simultaneously create any number of folders/directories:
mkdir dir1 dir2 dir3 dir_4
Verify it:
ls -l

Fig.01: How to create Folders/Directories In Linux/Unix with the mkdir command

More on file mode

The entry type character describes (the first character d rwxr-xr-x ) the type of file, as follows:

  1. : Regular file.
  2. b : Block special file.
  3. c : Character special file.
  4. d : Directory.
  5. l : Symbolic link.
  6. p : FIFO.
  7. s : Socket.
  8. w : Whiteout.

So basically d character in above entry tell us that it is a directory/folder. The next three fields are three characters ach: owner permissions, group permissions, and other permissions. Each field has three character positions:

Источник

How to Use ‘mkdir’ to Create Linux Directories

Make folders from a terminal with this simple command

What to Know

  • Open a terminal window in Linux.
  • Go to the folder where you want the new directory.
  • Enter the command mkdirname of directory.

This article explains how to create directories in Linux with the mkdir command. It also covers the switches used with mkdir and the proper syntax required to make the command work correctly.

How to Create a New Directory

Create new directories in Linux using the command line and the mkdir command.

For example, to create a directory called test, open a terminal window, navigate to the folder where you want the new directory, then enter mkdir test.

Change the Permissions of the New Directory

After creating a new folder, set the permissions so that only a certain user can access it or so that some people can edit files in the folder, but others have read-only permissions.

To continue with the example above, run the ls command to see the permissions for the folder called test:

Run the ls command in the folder where the test folder is located. If it’s your home directory (for example, you didn’t use the cd command), then you don’t have to change the directory here.

You should see something like this (but probably with several other entries, considering that there are other folders there):

The permissions are drwxrwxr-x, 2, owner, and group.

    • The d indicates that test is a directory.
      The first three letters following the d are the owner permissions for the directory specified by the owner’s name:
      r is for read.
    • w is for write.
    • x is for execute (which means you can access the folder).
  • The next three characters are the group permissions for the file specified by the group name. The options are r, w, and x. The hyphen means that a permission is missing. In the example above, anybody belonging to the group can access the folder and see the files, but can’t write to the folder.
  • The final characters are the permissions that all users have, and these are the same as the group permissions.

To change the permissions for a file or folder, use the chmod command. The chmod command lets you specify three numbers which set the permissions:

Add the numbers together for a mixture of permissions. For example, to attribute read and execute permissions, the number is 5 (4+1), or for read and write permissions, the number is 6 (4+2).

You must specify three numbers as part of the chmod command. The first number is for the owner permissions, the second is for the group permissions, and the last is for everyone else.

For example, for the owner to have full permissions, the group to have read and execute permissions, and anyone else to have no permissions, enter the following:

Use the chgrp command to change the group name that owns a folder. For example, to create a directory that the accountants in a company can access, first make the group accounts by typing the following:

If you don’t have the correct permission to create a group, use sudo to gain extra privileges or use the su command to switch to an account with valid permissions.

Next, change the group for a folder by typing the following:

To give the owner and everybody else in the accounts group read, write, and execute, but read-only access to others, use the following command:

How to Create a Directory and Set Permissions at the Same Time

You can create a directory and set the permissions for that directory at the same time using the following command:

This command creates a folder that everybody can access. It’s rare to create folders with this kind of permission.

Create a Folder and Any Parents That Are Required

You can create a directory structure without creating each individual folder, for example, to create folders for music as follows:

  • /home/music/rock/alicecooper
  • /home/music/rock/queen
  • /home/music/rap/drdre
  • /home/music/jazz/louisjordan

It takes time to create the rock folder for alice cooper and queen, followed by the rap and jazz folders for the others.

By specifying -p, you can create all the parent folders on the fly if these don’t exist:

For example, this mkdir command makes one of the folders listed above:

Get Confirmation That a Directory Was Created

By default, the mkdir command doesn’t tell you if the directory was created successfully. Usually, if no errors are shown, you can assume it worked. However, if you want more verbose output so that you know what’s been created, use the -v switch:

Источник

Читайте также:  Работа с openssl windows
Оцените статью