OSX:如何使 GNU Find 在脚本内默认查找?

OSX:如何使 GNU Find 在脚本内默认查找?

所以我通过自制程序安装了 GNU find。然后我创建了一个名为“find”的别名并将其指向 GNU find。

~
➜  alias | grep find
find=/usr/local/bin/gfind
tree='find . -print | sed -e '\''s;[^/]*/;|____;g;s;____|; |;g'\'

~
➜  which find       
find: aliased to /usr/local/bin/gfind

~
➜  find --version
find (GNU findutils) 4.7.0
Copyright (C) 2019 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Eric B. Decker, James Youngman, and Kevin Dalley.
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION FTS(FTS_CWDFD) CBO(level=2) 

我的问题是,在脚本内部(尝试过 bash 和 ZSH),当我使用“find”命令时,脚本总是想使用 Apple 提供的 find 命令。

关于如何修复有什么想法吗?谢谢。

这是我的示例脚本

#!/bin/bash 

source ~/Documents/environment-setup.sh
alias | grep find
which find
echo "running find --version"
find --version
echo "running gfind --version"
gfind --version

这是脚本的输出

~
➜  ./test.sh
alias find='/usr/local/bin/gfind'
/usr/bin/find
running find --version
find: illegal option -- -
usage: find [-H | -L | -P] [-EXdsx] [-f path] path ... [expression]
       find [-H | -L | -P] [-EXdsx] -f path [path ...] [expression]
running gfind --version
find (GNU findutils) 4.7.0
Copyright (C) 2019 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Eric B. Decker, James Youngman, and Kevin Dalley.
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION FTS(FTS_CWDFD) CBO(level=2)

答案1

ZSH 和 BASH 是不同的 shell,所以要小心,可能会有很多差异。你的例子中有两个问题。

问题 1:哪个

哪个不是 bash 中的内置命令,但在 zsh 中是。因为哪个不是内置命令,它可以解析别名

你必须使用类型

类型是两者的内置命令

巴什

MyMAC:tmp e444$ bash -l
MyMAC:tmp e444$ type which
which is /usr/bin/which
MyMAC:tmp e444$ type type
type is a shell builtin

中兴

MyMAC:tmp emas$ zsh -l
MyMAC% type which
which is a shell builtin
MyMAC% type type
type is a shell builtin

问题 2:别名

在 BASH 中,默认情况下,别名不会在非交互式 shell 中展开(脚本)

man bash

当 shell 非交互式时,别名不会扩展,除非

在 ZSH 中,别名被扩展

bash 的小例子b.sh和ZSHz.sh

文件b.sh

#!/bin/bash
mysql -v
alias mysql='/usr/local/Cellar/mysql55/5.5.30/bin/mysql'
mysql -v

MyMAC:tmp e444$ ./b.sh
./b.sh: line 2: mysql: command not found
./b.sh: line 4: mysql: command not found

文件 z.sh

#!/bin/zsh
mysql -v
alias mysql='/usr/local/Cellar/mysql55/5.5.30/bin/mysql'
mysql -v

MyMAC:tmp e444$ ./z.sh
./z.sh:2: command not found: mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

相关内容