Macos Bash脚本作为.command未正确执行

Macos Bash脚本作为.command未正确执行,macos,bash,shell,unix,terminal,Macos,Bash,Shell,Unix,Terminal,我有一个简单的脚本/命令: 当我从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 "tx

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

当我从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

然后它继续,递归地进入另一个命令从未尝试过的地方-我必须^C它,因为它已经疯了。它也不会创建新目录。。我在哪里?

我没有具体的解释,但有几点提示:

  • 您的脚本是否有
    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
    在当前目录中执行命令,而不管在哪里找到匹配的文件-如果希望在输入目录中创建所有目录,请使用
    -exec mkdir“$dir/$str”\
    相反,如果要创建在找到每个匹配文件的任何子目录中创建的目录,请使用
    -execdir mkdir“$str”\


因此,如果您在树上的任意位置发现一个文件包含
$txt
,那么您只是想在当前工作目录中创建一个目录?+1,但由于
echo
with options是如此不可移植,因此最好不要提及它(除非它附带了一个胖胖的、闪烁的粉色免责声明)…人们应该真正停止使用
echo-n
/
echo-e
,像推荐的那样使用
printf