繁体   English   中英

使用带有'which'的bash脚本中的命令

[英]Using commands in a bash script with 'which'

看看bash脚本有时我会看到这样的结构:

MYSQL=`which mysql`
$MYSQL -uroot -ppass -e "SELECT * FROM whatever"

在其他脚本中,命令(本例中为mysql )直接使用:

mysql -uroot -ppass -e "SELECT * FROM whatever"

那么,为什么以及何时应which使用和其命令-我从来没有见过echo与使用which ...

你可以做man which的细节:

描述

  which returns the pathnames of the files (or links) which would be executed in the current environment, had its arguments been given as commands in a strictly POSIX-conformant shell. It does this by search‐ ing the PATH for executable files matching the names of the arguments. It does not follow symbolic links. 

那么which mysql只返回mysql命令的当前路径。

但是which在您的示例中使用which只是确保忽略当前环境中为mysql设置的任何别名

但是还有另外一个clever shortcut ,以避免which在外壳。 你可以使用反斜杠调用mysql:

\mysql -uroot -ppass -e "SELECT * FROM whatever"

你的2个命令正在做的实际上是一样的

来自OP:使用的唯一原因是为了避免自定义别名可能出现的问题(比如alias mysql="mysql -upeter -ppaula" )。 而且由于人们不太可能为say echo设置别名,因此我们不需要这种带有echo的结构。 但是为mysql设置别名是很常见的(没人想记住并键入24个字符长密码)。

大部分他们都是一样的:

只要which 返回的二进制文件的绝对路径 当您使用某个执行脚本的第三个程序或准备此脚本将运行二进制文件的整个路径的环境时,有时会出现特殊情况。

就像调度程序一样。 如果您已安排了一个脚本,那么您将希望使用具有绝对路径的二进制文件。

因此:

mysql=`which mysql` 

要么

mysql=$(which mysql)

甚至

/usr/bin/mysql <flags>

调度程序中的脚本可能已运行

mysql ....<flags> 

但这不是前一篇文章中解释的保证。 别名可能是其中一个原因。

对于不使用绝对路径可带来的问题,请检查此链接

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM