Quero escrever o análogo Ubuntu de um "batch file" (um script shell). Mas eu não'não sei como usar chmod +x filename
comando para fazê-lo de modo que o script possa ser executado. Também não sei onde usá-lo.
chmod +x
em um arquivo (seu script) só significa, que você'vai torná-lo executável. Clique com o botão direito no seu script e escolha Properties -> Permissions -> Allow execution file as program, deixa você com o mesmo resultado exato do comando no terminal.
Se um arquivo no qual você quer mudar as permissões está localizado dentro do diretório do sistema você pode precisar ser root', assim: (tenha cuidado, enquanto utiliza o comando
sudo`)
sudo chmod +x /usr/share/testfolder/aFile
Também não está claro o que quer arquivar exactamente aqui. Por favor, edite a sua pergunta e dê mais alguns detalhes sobre o problema real!
Você também pode consultar esta pergunta, para obter mais informações: chmod u+x' versus 'chmod +x
Digite man chmod
em uma janela de terminal (Ctrl+Alt+T) e você'obterá a seguinte saída:
NAME: chmod - mudar os bits do modo de arquivo
**SYNOPSIS***
chmod [OPTION]... MODE[,MODE]... FILE...
chmod [OPTION]... OCTAL-MODE FILE...
chmod [OPTION]... --reference=RFILE FILE...
**DESCRIÇÃO***
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 E SETGID BITS***
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.
**OPÇÕES***
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]))+'.
Primeiro, o seu roteiro deve declarar qual o intérprete a usar. Você faz isso na primeira linha do arquivo. Se for's um script shell, deve ser #!/bin/sh
ou #!/bin/bash
.
Então aqui's um script que escreve seu nome de usuário: echo-whoami.sh
#!/bin/sh
echo $(whoami)
Para torná-lo executável, use chmod +x echo-whoami.sh
. Então você pode executá-lo usando ./echo-whoami.sh
.
Um arquivo de lote e um shell script são dois termos que significam efetivamente o mesmo sob Linux. O termo **script é muito mais utilizado***, no entanto.
O arquivo shell script mais simples contém apenas comandos como você'd digite-os na linha de comando (ou seja, o interpretador de comandos Bash). Em teoria você pode até substituir o intérprete por qualquer idioma que quiser (e ter um intérprete para). Para ser mais explícito, it's sugere que você inicie sua primeira linha com
#!/bin/sh
(se você quiser't máxima portabilidade com sistemas legados)
ou
#!/bin/bash
(se você quer alguns recursos extras, você provavelmente não'hoje não liga para isso)
Após esta linha introduza os seus comandos, um em cada linha. Há muitas construções extras além do escopo destas perguntas, veja man bash
ou http://www.tldp.org/LDP/Bash-Beginners-Guide/Bash-Beginners-Guide.pdf (para Iniciantes) ou http://www.tldp.org/LDP/abs/abs-guide.pdf (para perguntas mais avançadas).
Para executar realmente o seu script, há dois requisitos: Primeiro, o processo de interpretação precisa de ler o ficheiro, e segundo, verifica se está marcado como executável. Por razões de conveniência é útil também's ser capaz de escrever no seu script (para que você possa fazer alterações ou correções devem ser necessárias).
Assumindo ainda que você quer que os membros da equipe e outros também sejam capazes de executar (e ver) seu script, mas que você não'não quer que eles o manipulem, a combinação de
a+x
ou +x
, já que a
é o padrão),a+r' ou
+r', pois `a' é novamente o padrão),u=w
)são normalmente valores sensatos das suas permissões de arquivo. Você pode digitar as ações individuais concatenadas, separadas com uma vírgula.
Embora este "action language" seja muito fascinante (note a diferença dos operadores +
e =
que resultam em resultados diferentes, dependendo da configuração de permissão antes de você mudá-los), eles são tediosos de digitar.
Como todas as ações criam máscaras de bit que são aplicadas internamente, você pode digitar as máscaras de bit (veja man chmod
para detalhes) também diretamente.
Para um shellscript chmod 755 myscript.sh faz mais sentido em pelo menos 95% de todos os casos.