Make directory linux script

Как создавать каталоги в Linux (команда mkdir)

В системах Linux вы можете создавать новые каталоги либо из командной строки, либо с помощью файлового менеджера вашего рабочего стола. Команда, позволяющая создавать каталоги (также известные как папки), — это mkdir .

В этом руководстве рассматриваются основы использования команды mkdir , включая повседневные примеры.

Синтаксис команды Linux mkdir

Синтаксис команды mkdir следующий:

Команда принимает в качестве аргументов одно или несколько имен каталогов.

Как создать новый каталог

Чтобы создать каталог в Linux, передайте имя каталога в качестве аргумента команды mkdir . Например, чтобы создать новый каталог newdir вы должны выполнить следующую команду:

Вы можете убедиться, что каталог был создан, перечислив его содержимое с помощью команды ls :

При указании только имени каталога без полного пути он создается в текущем рабочем каталоге.

Текущий рабочий каталог — это каталог, из которого вы запускаете команды. Чтобы изменить текущий рабочий каталог, используйте команду cd .

Чтобы создать каталог в другом месте, вам необходимо указать абсолютный или относительный путь к файлу родительского каталога. Например, чтобы создать новый каталог в каталоге /tmp вы должны ввести:

Если вы попытаетесь создать каталог в родительском каталоге, в котором у пользователя недостаточно прав, вы получите сообщение об ошибке Permission denied :

Параметр -v ( —verbose ) указывает mkdir печатать сообщение для каждого созданного каталога.

Как создать родительские каталоги

Родительский каталог — это каталог, который находится над другим каталогом в дереве каталогов. Чтобы создать родительские каталоги, используйте параметр -p .

Допустим, вы хотите создать каталог /home/linuxize/Music/Rock/Gothic :

Если какой-либо из родительских каталогов не существует, вы получите сообщение об ошибке, как показано ниже:

Вместо того, чтобы создавать недостающие родительские каталоги один за другим, вызовите команду mkdir с параметром -p :

Когда используется опция -p , команда создает каталог, только если он не существует.

Если вы попытаетесь создать каталог, который уже существует, а параметр -p не mkdir , mkdir выведет сообщение об ошибке File exists :

Как установить разрешения при создании каталога

Чтобы создать каталог с определенными разрешениями, используйте параметр -m ( -mode ). Синтаксис для назначения разрешений такой же, как и для команды chmod .

В следующем примере мы создаем новый каталог с разрешениями 700 , что означает, что только пользователь, создавший каталог, сможет получить к нему доступ:

Когда опция -m не используется, вновь созданные каталоги обычно имеют права доступа 775 или 755 , в зависимости от значения umask .

Как создать несколько каталогов

Чтобы создать несколько каталогов, укажите имена каталогов в качестве аргументов команды, разделенные пробелом:

Команда mkdir также позволяет создать сложное дерево каталогов с помощью одной команды:

Приведенная выше команда создает следующее дерево каталогов :

Выводы

Команда mkdir в Linux используется для создания новых каталогов.

Для получения дополнительной информации о mkdir посетите страницу руководства mkdir .

Если у вас есть вопросы, не стесняйтесь оставлять комментарии ниже.

Источник

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.

Читайте также:  Настройка принтеров для пользователей windows

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:

Читайте также:  Windows all users desktop folder

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:

Источник

How do I make an entire directory executable?

I have an entire folder dedicated to python scripts.

I’m tired of doing chmod on every new python script that I write.

Is there a way to make every file inside my folder executable if it is a python script?

It would be nice to have a script that checks whenever a new .py script is created and if there is a new .py script make it executable right there on the spot.

5 Answers 5

Another good option is Incron. It works on inotify with specifiable conditions for a given location.

So I can say watch this folder, when you see a file created, run a command.

Just as a sample incrontab.

One could similarly use the path/file as arguments to a bash script to allow it to filter by .py extensions if needed.

Will make executable all current .py files in directory /path/to/python/scripts/dir.

I’m not aware of an auto-tool as you describe. It might be possible to have a macro in your editor that could do this, but not with the editor I use. 😉

As a first step, you could try this in your

    This runs chmod +x on the filename for all .py files when you write to them. Looking at the list of events ( :h events ), I can’t find an event where a new file is created, so I had to settle for running each time it is written to.

The first time the chmod is applied, the file gets changed, and vim will alert you to that:

I tried a couple of tricks to make it autoread just for this change, but no luck. So you’ll have to press Enter twice.

When initiated, the script below automatically changes the permissions of all files of a given type (extension) in a directory (one time). After that, the script checks the directory every 5 seconds for newly added files, and changes the permissions if the file is of the given type (in this case a .py file)

It has a few options: in this case, it makes the newly added files executable, but other actions are possible too, as defined in the line: command = «chmod +x» . Additionally, you can define (change) on what kind of files (language extensions) the action should be performed.

How to use

Copy the script below into an empty file. Save it as change_permission.py and run it in the background by the command:

Thanks for contributing an answer to Ask Ubuntu!

  • Please be sure to answer the question. Provide details and share your research!
  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Источник

How to Use mkdir Command to Make or Create a Linux Directory

Home » SysAdmin » How to Use mkdir Command to Make or Create a Linux Directory

What is the mkdir Command in Linux?

The mkdir command in Linux/Unix allows users to create or make new directories. mkdir stands for “make directory.”

With mkdir , you can also set permissions, create multiple directories (folders) at once, and much more.

This tutorial will show you how to use the mkdir command in Linux.

  • Linux or UNIX-like system.
  • Access to a terminal/command line.
  • A user with permissions to create and change directory settings.
Читайте также:  Avast для windows 10 последняя версия

mkdir Command Syntax in Linux

The basic command for creating directories in Linux consists of the mkdir command and the name of the directory. As you can add options to this command, the syntax looks like this:

To understand better how to use mkdir , refer to the examples we provide in the rest of the guide.

Tip: Use cd to navigate to the directory where you want to create a sub-directory. You can also use the direct path. Use ls to list the directories in the current location.

How to Make a New Directory In Linux

To create a directory using the terminal, pass the desired name to the mkdir command.

In this example, we created a directory Linux on the desktop. Remember commands in Linux and options are case sensitive.

If the operation is successful, the terminal returns an empty line.

To verify, use ls .

Note: To create a hidden directory, follow our guide on how to show and create hidden files in Linux.

How to Create Multiple Directories with mkdir

You can create directories one by one with mkdir, but this can be time-consuming. To avoid that, you can run a single mkdir command to create multiple directories at once.

To do so, use the curly brackets <> with mkdir and state the directory names, separated by a comma.

Do not add any spaces in the curly brackets for the directory names. If you do, the names in question will include the extra characters:

How to Make Parent Directories

Building a structure with multiple subdirectories using mkdir requires adding the -p option. This makes sure that mkdir adds any missing parent directories in the process.

For example, if you want to create “dirtest2 in “dirtest1 inside the Linux directory (i.e., Linux/dirtest1/dirtest2), run the command:

Use ls -R to show the recursive directory tree.

Without the -p option, the terminal returns an error if one of the directories in the string does not exist.

How to Set Permissions When Making a Directory

The mkdir command by default gives rwx permissions for the current user only.
To add read, write, and execute permission for all users, add the -m option with the user 777 when creating a directory.

To create a directory DirM with rwx permissions:

To list all directories and show the permissions sets: -l

The directory with rwx permissions for all users is highlighted. As you can see on the image above, two other directories by default have rwx permission for the owner, xr for the group and x for other users.

How to Verify Directories

When executing mkdir commands, there is no feedback for successful operations. To see the details of the mkdir process, append the -v option to the terminal command.

Let’s create a Details directory inside Dir1 and print the operation status:

By getting the feedback from the process, you do not have to run the ls command to verify the directory was created.

mkdir Command Options and Syntax Summary

Option / Syntax Description
mkdir directory_name Creates a directory in the current location
mkdir Creates multiple directories in the current location. Do not use spaces inside <>
mkdir –p directory/path/newdir Creates a directory structure with the missing parent directories (if any)
mkdir –m777 directory_name Creates a directory and sets full read, write, execute permissions for all users
mkdir –v directory_name(s) Creates a directory in the current location

Note: Learn to fully manage directories by learning to move a directory in a system running a Linux distribution.

This guide covered all commands you need to create directories in Linux.

Now you understand how to use the Linux mkdir command. It’s straightforward and simple to use.

If you have the necessary permissions, there should be no error messages when you follow the instructions in this article.

Источник

Оцените статью