- Qual è la differenza tra i modi?
da 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.
Non ci sono differenze tra i due modi.
C'è solo una nota: evalconcatenati tutti i suoi argomenti, che viene quindi eseguito come un singolo comando. sourcelegge i contenuti di un file e li esegue. evalpuò solo costruire comandi dai suoi argomenti, no stdin. Quindi non puoi fare così:
printf "ls" | eval
Il tuo esempio fornisce lo stesso risultato, ma lo scopo di evaled sourceè diverso. sourceviene generalmente utilizzato per fornire una libreria per altri script, mentre evalviene utilizzato solo per valutare i comandi. evalSe possibile, dovresti evitare di usarlo , perché non esiste alcuna garanzia che la stringa valutata sia pulita; dobbiamo fare alcuni controlli di sanità mentale, usando subshellinvece.
- Se eseguiamo alcuni comandi tra () o {}, quale è più preferito?
Quando si eseguono comandi di sequenza all'interno di parentesi graffe { }, tutti i comandi vengono eseguiti nella shell corrente , anziché in una shell secondaria (che è il caso se si esegue tra parentesi (consultare il riferimento bash )).
L'utilizzo subshell ( )utilizza più risorse, ma l'ambiente attuale non è interessato. L'utilizzo { }esegue tutti i comandi nella shell corrente, quindi l'ambiente è interessato. A seconda del tuo scopo, puoi sceglierne uno.