【问题标题】:Bash script as .command not executing properly作为 .command 的 Bash 脚本未正确执行
【发布时间】:2014-04-03 04:06:54
【问题描述】:

我有一个简单的脚本/命令:

当我从 shell 运行它时:

 txt=testfile
 find ~/Desktop/Rory/Test -type f -exec grep $txt {} \; -exec mkdir $txt \; 

结果是:

Binary file ./TEST.zip matches
and it makes a new directory named testfile

当我将它保存为 .command 时:

echo "cd: \c"
read dir
echo "txt: \c"
read str
find $dir -type f -exec grep $str {} \; -exec mkdir $str \;

chmod 755 并双击它我得到:

Last login: Wed Apr  2 20:44:14 on ttys004
zipher:~ Rory$ /Users/Rory/Desktop/CD.command ; exit;
cd: \c
/Users/Rory/Desktop/Test
txt: \c
txt

然后它继续到go to hell in a handbasket,递归地进入另一个命令从未冒险过的地方——我必须 ^C 它因为它已经疯了。它也不会创建新目录.. 我在哪里screw the pooch

【问题讨论】:

  • 因此,如果您在树上的任何位置找到包含$txt 的文件,您只是想在当前工作目录中创建一个目录?

标签: macos bash shell unix terminal


【解决方案1】:

我没有具体的解释,只是指点一下:

  • 您的脚本是否有bash shebang 行(文件的第一行是#!/usr/bin/env bash)?我见过没有它的 OSX 会表现得很奇怪。

  • 我假设提示字符串中的 \c 旨在抑制尾随换行符 - 默认情况下,这在 bash 中不起作用 - 您需要使用 -e 调用 echo,或者 -最好 - 只使用 printf - 例如,printf "cd: "

  • 我建议您双引号在您的find 命令中引用变量,这样如果输入的路径或字符串包含嵌入的空格或其他字符,该命令就不会中断。对外壳有特殊意义。

到目前为止,我们得到:

printf "cd: "
read dir
printf "txt: "
read str
find "$dir" -type f -exec grep -l "$str" {} \; -exec mkdir "$str" \;

还有更多:

  • 注意find处理指定目录的整个子树;如果只想匹配当前目录下的文件,添加-maxdepth 1

  • 请注意,-exec当前 目录中执行命令,无论在何处找到匹配文件 - 如果您希望在输入目录中创建所有目录,请使用 @相比之下,987654334@,如果要创建在找到每个匹配文件的任何子目录中创建的目录,请使用-execdir mkdir "$str" \;

【讨论】:

  • +1,但由于echo with options 非常不便携,最好不要提及它(除非它带有一个胖乎乎的、闪烁的粉红色免责声明)......人们真的应该停止使用echo -n/echo -e 并使用 printf 推荐。
猜你喜欢
  • 2012-02-07
  • 2015-01-21
  • 2012-10-12
  • 1970-01-01
  • 2013-10-18
  • 1970-01-01
  • 2022-01-27
  • 1970-01-01
  • 2020-06-14
相关资源
最近更新 更多