- Qual é a diferença entre as maneiras?
de bash manpage:
eval [arg ...]
The args are read and concatenated together into a single com‐
mand. This command is then read and executed by the shell, and
its exit status is returned as the value of eval. If there are
no args, or only null arguments, eval returns 0.
source filename [arguments]
Read and execute commands from filename in the current shell
environment and return the exit status of the last command exe‐
cuted from filename. If filename does not contain a slash, file
names in PATH are used to find the directory containing file‐
name. The file searched for in PATH need not be executable.
When bash is not in posix mode, the current directory is
searched if no file is found in PATH. If the sourcepath option
to the shopt builtin command is turned off, the PATH is not
searched. If any arguments are supplied, they become the posi‐
tional parameters when filename is executed. Otherwise the
positional parameters are unchanged. The return status is the
status of the last command exited within the script (0 if no
commands are executed), and false if filename is not found or
cannot be read.
Não há diferenças entre as duas maneiras.
Há apenas uma nota: evalconcatenou todos os seus argumentos, que são executados como um único comando. sourcelê o conteúdo de um arquivo e os executa. evalsó pode criar comandos a partir de seus argumentos, não stdin. Então você não pode fazer assim:
printf "ls" | eval
Seu exemplo fornece o mesmo resultado, mas o objetivo evale sourceé diferente. sourceé geralmente usado para fornecer uma biblioteca para outros scripts, enquanto evalé usado apenas para avaliar comandos. Você deve evitar o uso, evalse possível, porque não há garantia de que a cadeia avaliada esteja limpa; devemos fazer algumas verificações de sanidade, usando em seu subshelllugar.
- Se executarmos alguns comandos em () ou {}, qual é o preferido?
Quando você executa comandos de sequência dentro de chaves { }, todos os comandos são executados no shell atual , em vez de um subshell (que é o caso se você executar entre parênteses (consulte a referência do bash )).
O uso subshell ( )usa mais recursos, mas seu ambiente atual não é afetado. O uso { }executa todos os comandos no shell atual, para que seu ambiente seja afetado. Dependendo do seu objetivo, você pode escolher um deles.