Linux скрипт создать папку

Bash скрипт для создания директории

Я возиться со сценариями, я могу создать сценарий, который при запуске запрашивает у меня имя для нового каталога, создает его, затем создает несколько файлов, выводит строки, а затем удаляет все это.

Я хотел бы немного изменить его, чтобы он сам создавал и называл каталог!

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

#!/bin/bash echo "Give a directory name to create:" read NEW_DIR ORIG_DIR=$(pwd) [[ -d $NEW_DIR ]] && echo $NEW_DIR already exists, aborting && exit mkdir $NEW_DIR cd $NEW_DIR pwd for n in 9 8 7 6 5 4 3 2 1 0 do touch file$n done ls file? for names in file? do echo This file is named $names > $names done cat file? cd $ORIG_DIR rm -rf $NEW_DIR echo "Goodbye" 

4 ответа

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

замените следующую строку в вашем скрипте:

NEW_DIR="new_dir_hard_coded_value" 

Если вы хотите сюрприз, вместо жесткого кодирования имени, вы можете использовать технику для генерации случайной строки, например

Это устанавливает NEW_DIR до строки из восьми буквенно-цифровых символов. Каждый раз, когда вы запускаете скрипт, новый каталог будет иметь другое случайное имя.

Или, чтобы получить случайное слово, выберите словарь из /usr/share/dict/ и использовать shuf , например:

$ shuf -n1 /usr/share/dict/british-english soupier $ shuf -n1 /usr/share/dict/british-english penguins 
NEW_DIR=$(shuf -n1 /usr/share/dict/british-english) mkdir "$NEW_DIR" . 

Вы могли бы даже пойти еще дальше: вы можете сказать «читать», чтобы предложить предложение для имени папки, принять его, нажав return или изменить его, как вам нравится:

read -p "Give a directory name to create: " -ei "default_name" NEW_DIR; 
Give a directory name to create: default_name 

Чтобы объединить с вышеупомянутыми предложениями, вы можете сделать следующее:

# pre-set NEW_DIR to a value or to any random string # as suggested in the other answers NEW_DIR="default_name" # Prompt for new directory name, suggesting previously selected default answer read -p "Give a directory name to create: " -ei "$NEW_DIR" NEW_DIR; 

Обратите внимание, что чтение -p «текст» запросит текст и попросит ответить в той же строке. Если вы хотите придерживаться своего кода и попросить его о 2-строчном формате, вы можете сделать

echo "Give a directory name to create:" read -ei "$NEW_DIR" NEW_DIR 

Источник

Bash script that creates a directory structure

I’ve been googling all night trying to find a way to create a script that creates a directory structure. That looks something like this:

/ shared shared/projects shared/series shared/movies shared/movies/action
shared backup shared data shared projects shared projcets series shared projects movies shared projects movies action

I want to create a script that reads each line in the file and run the following for each line: If the directory exist, it places itself in the directory and create the structure from there, if The directory doesn’t exist, create it.
When all entries in the row have been preceded by, go back to original directory and read the next line. My system is Ubuntu 10.10. So far I’ve done this, but it doesn’t work.

#!/bin/bash pwd=$(pwd) for structure in $ do if [ $structure ] then cd $structure else mkdir $structure fi done cd $pwd 

7 Answers 7

You can use mkdir -p shared/projects/movies/action to create the whole tree: it will create shared , then shared/projects , then shared/projects/movies , and shared/projects/movies/action .

Читайте также:  Поднять интерфейс linux centos

So basically you need script that runs mkdir -p $dir where $dir is the leaf directory of your directory tree.

For extremely complicated directory structures use <> like so: mkdir -p shared/> You can nest the braces as much as you need to. This will create the shared folder with the subfolders backup, data, and projects. The projects folder will have the subfolder series and movies. The movie folder will have the subfolder action. Source

If struct.txt contains the directory structure that you mention, then just run:

sed '/^$/d;s/ /\//g' struct.txt | xargs mkdir -p 

sed will remove blank lines and make the remaining lines look like directory paths.
xargs will take each line and pass it as a parameter to mkdir .
mkdir will make the directory and the -p flag will create any parent directories if needed.

mkdir has a flag -p that creates all the parent directories of the directory you’re creating if needed. you can just just read each line, turn it into a path (i.e. s/ /\//g ) and call mkdir -p $path on each line

For my solution it was important to me:

a) I wanted to be able to edit the directory structure directly in my bash script so that I didn’t have to jump back and forth between two files

b) The code for the folders should be as clear as possible without redundancy with the same paths, so that I can change it easily

# Creates the folder structure defined in folder structure section below function createFolderStructure() < depth="1" while (( "$#" )); do while (( $1 != $depth )); do cd .. (( depth-- )) done shift mkdir "$1" cd "$1" (( depth++ )) shift done while (( 1 != $depth )); do cd .. (( depth-- )) done ># Folder Structure Section read -r -d '' FOLDERSTRUCTURE  

Git needs files to record directories. So I put a readme file in each directory and extended the script as follows:

# Creates the folder structure defined in folder structure section below function createFolderStructure() < depth="1" while (( "$#" )); do while (( $1 != $depth )); do cd .. (( depth-- )) done shift mkdir "$1" cd "$1" (( depth++ )) shift shift out="" while [[ "$1" != "-" ]]; do out=$out" ""$1" shift done shift echo "$out" >README.md done while (( 1 != $depth )); do cd .. (( depth-- )) done > # If you like you can read in user defined values here and use them as variables in the folder structure section, e.g. # echo -n "Enter month of films" # read month # . # 1 shared - Folder for shared stuff - # 2 $month - Films from month $month - # 3 projects - Folder for projects - # . # Folder Structure Section read -r -d '' FOLDERSTRUCTURE  

Источник

Bash Create Directory

Bash Create Directory

  1. Create a Folder if It Doesn’t Exist in Bash
  2. Use while Loop to Create a Folder in Bash
  3. Use the Recursion Method to Create a Folder in Bash

This article demonstrates how to create a folder if it doesn’t already exist in Bash.

Create a Folder if It Doesn’t Exist in Bash

We use the mkdir command to create a new directory in Linux. We use mkdir -p to avoid the error message.

Using the mkdir command, you have to make every file one by one but, with the mkdir-p , it will create it at once.

We can create a folder if it doesn’t already exist in Bash in two different ways. We can do that by using a while loop in the function or the recursion method.

We can check the condition of whether the directory already exists or not by using this if[ -d $DirName ] in the Bash script. We will create a Bash function that will take the directory name as input from the user.

It will create a new directory if the directory doesn’t exist. If the directory already exists, it will prompt the user to enter a different name.

Use while Loop to Create a Folder in Bash

In the while loop, we will get the input from the user by using the read command in the Bash script. The user will enter the directory name that he wants to create.

If the entered directory name already exists in that case, the if[ -d $Dirname] condition will return true. It will display a message to the user that the directory already exists.

It will prompt the user to enter a different directory name. This checking condition will continue until the user enters a directory name in the input that doesn’t already exist.

When the user enters a directory name that doesn’t already exist in that case, the if[ -d $Dirname] condition will return false, and the else block will execute that will create the new directory.

It will display the new directory has been successfully created to the user, and the loop will break.

#!/bin/bash  function mkdirectory()  while [ true ] do if [ -d $DirName ] then echo "Directory Already exists:" echo "Enter Different Name: " read DirName else mkdir "$DirName" echo " the new directory has been successfully created: $DirName" break fi done > echo "Enter New DirName: " read DirName mkdirectory 

Источник

Linux скрипт создать папку

NAME

SYNOPSIS

mkdir [-p][-m mode] dir. 

DESCRIPTION

The mkdir utility shall create the directories specified by the operands, in the order specified. For each dir operand, the mkdir utility shall perform actions equivalent to the mkdir() function defined in the System Interfaces volume of IEEE Std 1003.1-2001, called with the following arguments: 1. The dir operand is used as the path argument. 2. The value of the bitwise-inclusive OR of S_IRWXU, S_IRWXG, and S_IRWXO is used as the mode argument. (If the -m option is specified, the mode option-argument overrides this default.)

OPTIONS

The mkdir utility shall conform to the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines. The following options shall be supported: -m mode Set the file permission bits of the newly-created directory to the specified mode value. The mode option-argument shall be the same as the mode operand defined for the chmod utility. In the symbolic_mode strings, the op characters '+' and '-' shall be interpreted relative to an assumed initial mode of a= rwx; '+' shall add permissions to the default mode, '-' shall delete permissions from the default mode. -p Create any missing intermediate pathname components. For each dir operand that does not name an existing directory, effects equivalent to those caused by the following command shall occur: mkdir -p -m $(umask -S),u+wx $(dirname dir) && mkdir [-m mode] dir where the -m mode option represents that option supplied to the original invocation of mkdir, if any. Each dir operand that names an existing directory shall be ignored without error.

OPERANDS

The following operand shall be supported: dir A pathname of a directory to be created.

STDIN

INPUT FILES

ENVIRONMENT VARIABLES

The following environment variables shall affect the execution of mkdir: LANG Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of IEEE Std 1003.1-2001, Section 8.2, Internationalization Variables for the precedence of internationalization variables used to determine the values of locale categories.) LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_CTYPE Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments). LC_MESSAGES Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error. NLSPATH Determine the location of message catalogs for the processing of LC_MESSAGES . 

ASYNCHRONOUS EVENTS

STDOUT

STDERR

The standard error shall be used only for diagnostic messages.

OUTPUT FILES

EXTENDED DESCRIPTION

EXIT STATUS

The following exit values shall be returned: 0 All the specified directories were created successfully or the -p option was specified and all the specified directories now exist. >0 An error occurred.

CONSEQUENCES OF ERRORS

Default. The following sections are informative. 

APPLICATION USAGE

The default file mode for directories is a= rwx (777 on most systems) with selected permissions removed in accordance with the file mode creation mask. For intermediate pathname components created by mkdir, the mode is the default modified by u+ wx so that the subdirectories can always be created regardless of the file mode creation mask; if different ultimate permissions are desired for the intermediate directories, they can be changed afterwards with chmod. Note that some of the requested directories may have been created even if an error occurs.

EXAMPLES

RATIONALE

The System V -m option was included to control the file mode. The System V -p option was included to create any needed intermediate directories and to complement the functionality provided by rmdir for removing directories in the path prefix as they become empty. Because no error is produced if any path component already exists, the -p option is also useful to ensure that a particular directory exists. The functionality of mkdir is described substantially through a reference to the mkdir() function in the System Interfaces volume of IEEE Std 1003.1-2001. For example, by default, the mode of the directory is affected by the file mode creation mask in accordance with the specified behavior of the mkdir() function. In this way, there is less duplication of effort required for describing details of the directory creation.

FUTURE DIRECTIONS

SEE ALSO

chmod() , rm , rmdir() , umask() , the System Interfaces volume of IEEE Std 1003.1-2001, mkdir()

Источник

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