Я хочу написать аналог Ubuntu для «пакетного файла» (сценарий оболочки). Но я не знаю, как использовать команду chmod +x filename
, чтобы скрипт мог быть запущен. Я также не знаю, где его использовать.
chmod +x
на файле (Ваш сценарий) только означает, что Вы сделаете его исполняемым файлом. Щелкните правой кнопкой по своему сценарию, и выбрал Properties-> Permissions-> файл выполнения Allow как программа, листы Вы с тем же самым результатом как команда в терминале.
Если файл, на котором Вы хотите изменить полномочия, расположен в рамках системного каталога, Вы, возможно, должны быть root
, как так: (будьте осторожны при использовании sudo
команда)
sudo chmod +x /usr/share/testfolder/aFile
Также не ясно, что точно Вы хотите заархивировать здесь. Отредактируйте свой вопрос и предоставьте еще некоторую подробную информацию о фактической проблеме!
Можно также обратиться к этому вопросу для получения дополнительной информации: chmod u+x' по сравнению с 'chmod +x
Ввести man chmod
в окне терминала (Ctrl+Alt+T) и Вы получите следующий вывод:
Имя: chmod - изменяют биты режима файла
РЕЗЮМЕ
chmod [OPTION]... MODE[,MODE]... FILE...
chmod [OPTION]... OCTAL-MODE FILE...
chmod [OPTION]... --reference=RFILE FILE...
ОПИСАНИЕ
This manual page documents the GNU version of chmod. chmod changes the
file mode bits of each given file according to mode, which can be either
a symbolic representation of changes to make, or an octal number repre‐
senting the bit pattern for the new mode bits.
The format of a symbolic mode is [ugoa...][[+-=][perms...]...], where
perms is either zero or more letters from the set rwxXst, or a single
letter from the set ugo. Multiple symbolic modes can be given, sepa‐
rated by commas.
A combination of the letters ugoa controls which users' access to the
file will be changed: the user who owns it (u), other users in the
file's group (g), other users not in the file's group (o), or all users
(a). If none of these are given, the effect is as if a were given, but
bits that are set in the umask are not affected.
The operator + causes the selected file mode bits to be added to the
existing file mode bits of each file; - causes them to be removed; and =
causes them to be added and causes unmentioned bits to be removed except
that a directory's unmentioned set user and group ID bits are not
affected.
The letters rwxXst select file mode bits for the affected users: read
(r), write (w), execute (or search for directories) (x), execute/search
only if the file is a directory or already has execute permission for
some user (X), set user or group ID on execution (s), restricted dele‐
tion flag or sticky bit (t). Instead of one or more of these letters,
you can specify exactly one of the letters ugo: the permissions granted
to the user who owns the file (u), the permissions granted to other
users who are members of the file's group (g), and the permissions
granted to users that are in neither of the two preceding categories
(o).
A numeric mode is from one to four octal digits (0-7), derived by adding
up the bits with values 4, 2, and 1. Omitted digits are assumed to be
leading zeros. The first digit selects the set user ID (4) and set
group ID (2) and restricted deletion or sticky (1) attributes. The sec‐
ond digit selects permissions for the user who owns the file: read (4),
write (2), and execute (1); the third selects permissions for other
users in the file's group, with the same values; and the fourth for
other users not in the file's group, with the same values.
chmod never changes the permissions of symbolic links; the chmod system
call cannot change their permissions. This is not a problem since the
permissions of symbolic links are never used. However, for each sym‐
bolic link listed on the command line, chmod changes the permissions of
the pointed-to file. In contrast, chmod ignores symbolic links encoun‐
tered during recursive directory traversals.
SETUID И БИТЫ SETGID
chmod clears the set-group-ID bit of a regular file if the file's group
ID does not match the user's effective group ID or one of the user's
supplementary group IDs, unless the user has appropriate privileges.
Additional restrictions may cause the set-user-ID and set-group-ID bits
of MODE or RFILE to be ignored. This behavior depends on the policy and
functionality of the underlying chmod system call. When in doubt, check
the underlying system behavior.
ОПЦИИ
Change the mode of each FILE to MODE.
-c, --changes
like verbose but report only when a change is made
--no-preserve-root
do not treat `/' specially (the default)
--preserve-root
fail to operate recursively on `/'
-f, --silent, --quiet
suppress most error messages
-v, --verbose
output a diagnostic for every file processed
--reference=RFILE
use RFILE's mode instead of MODE values
-R, --recursive
change files and directories recursively
--help display this help and exit
--version
output version information and exit
Each MODE is of the form `[ugoa]*([-+=]([rwxXst]*|[ugo]))+'.
Во-первых, Ваш сценарий должен объявить который интерпретатор использовать. Вы делаете это в первой строке файла. Если это - сценарий оболочки, это должно быть #!/bin/sh
или #!/bin/bash
.
, Таким образом, вот сценарий, который пишет Ваше имя пользователя: эхо-whoami.sh
#!/bin/sh
echo $(whoami)
Для создания этого исполняемым файлом используйте chmod +x echo-whoami.sh
. Затем можно выполнить его с помощью ./echo-whoami.sh
.
Пакетный файл и сценарий оболочки являются двумя условиями, означающими эффективно то же в соответствии с Linux. Термин сценарий намного чаще используется, все же.
Самый простой файл сценария оболочки просто содержит команды, поскольку Вы ввели бы их на командной строке (то есть, интерпретатор команд Bash). В теории можно даже заменить интерпретатор любым языком, который Вы любите (и имейте интерпретатор для). Чтобы быть более явным, это предложило, чтобы Вы запустили свою первую строку с
#!/bin/sh
(если Вы wan't максимальная мобильность с унаследованными системами)
или
#!/bin/bash
(если Вы хотите некоторые дополнительные функции, Вы, вероятно, не заботитесь о сегодня),
После этой строки вводят Ваши команды, один на каждой строке. Существует много дополнительных конструкций вне объема этого, подвергает сомнению, посмотрите man bash
или http://www.tldp.org/LDP/Bash-Beginners-Guide/Bash-Beginners-Guide.pdf (для Новичков) или http://www.tldp.org/LDP/abs/abs-guide.pdf (для более усовершенствованных вопросов).
Для фактического запущения скрипта существует два требования: Во-первых, процесс интерпретатора должен считать файл, и второй, он проверяет, отмечен ли он как исполняемый файл. Поскольку удобство обосновывает, что также полезно смочь записать в Ваш сценарий (таким образом, можно внести изменения, или меры должны должными быть быть).
Предположение далее, что Вы хотите, чтобы члены команды и другой также смогли работать (и видеть) Ваш сценарий, но что Вы не хотите, чтобы они управляли им, комбинация
a+x
или +x
, как a
значение по умолчанию),a+r
или +r
, как a
снова значение по умолчанию),u=w
)обычно разумные значения Ваших полномочий файла. Можно ввести единственные действия, связанные, разделенные с запятой.
В то время как этот "язык действия" является очень захватывающим (отметьте различие +
и =
оператор, которые приводят к различным результатам в зависимости от разрешения, устанавливающего перед изменением их), они утомительны для ввода.
Поскольку все действия создают битовые маски, которые применяются внутренне, можно ввести битовые маски (см. man chmod
для деталей) также непосредственно.
Поскольку сценарий оболочки chmod 755 myscript.sh имеет большую часть смысла по крайней мере в 95% всех случаев.