命令路径作为 shell 脚本中的变量

Ste*_*eve 5 shell scripting path

在 shell 脚本中运行外部实用程序时的最佳实践是什么。例如,如果我想在多个脚本中运行“gzip”以确保使用特定的 gzip 二进制文件,我是否应该将二进制文件的完整路径设为变量并在整个脚本中使用该变量?

GZIP=/home/me/bin/gzip
$GZIP somefile
$GZIP anotherfile
Run Code Online (Sandbox Code Playgroud)

还是为每次调用二进制文件的路径进行硬编码是更好的做法?

/home/me/bin/gzip somefile
/home/me/bin/gzip anotherfile
Run Code Online (Sandbox Code Playgroud)

还是设置和依赖路径更好?

PATH=/home/me/bin:$PATH
gzip somefile
gzip anotherfile
Run Code Online (Sandbox Code Playgroud)

我没有以 root 身份运行脚本,因此可维护性和可移植性比用户安全性更重要。

Pau*_*ce. 2

我认为第一个选择是最好的。你会发现它或类似的:

SOMEPATH=/path/to/somewhere
EXEC_ONE=exec_foo
EXEC_TWO=exec_bar

$SOMEPATH/$EXEC_ONE --argument baz_file
Run Code Online (Sandbox Code Playgroud)

在许多系统脚本中。

您可以使用条件来测试是否存在甚至兼容性、可用选项等,并相应地设置变量。