如何在macbook pro上运行bash脚本?

时间:2012-02-04 05:33:16

标签: macos bash

我从MacBook Pro打开了“终端”,并尝试从“Bash初学者指南”中运行一些bash脚本:

首先我检查了PATH环境设置和当前工作文件夹,其中包含一个脚本“script1.sh”:

unknown_b8-8d-1b-3d-0b-3d:myscript liuren$ echo $PATH
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin
unknown_b8-8d-1b-3d-0b-3d:myscript liuren$ pwd
/Users/liuren/Documents/myscript
unknown_b8-8d-1b-3d-0b-3d:myscript liuren$ ls
script1.sh

然后我将PATH设置为包含当前工作文件夹,它似乎成功了:

unknown_b8-8d-1b-3d-0b-3d:myscript liuren$ export PATH="$PATH:/Users/liuren/Documents/myscript"
unknown_b8-8d-1b-3d-0b-3d:myscript liuren$ echo $PATH
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/Users/liuren/Documents/myscript

然而我无法运行“script1.sh”:

unknown_b8-8d-1b-3d-0b-3d:myscript liuren$ script1.sh
#: bad interpreter: No such file or directoryt1.sh: /bin/bash

unknown_b8-8d-1b-3d-0b-3d:myscript liuren$ ./script1.sh
#: bad interpreter: No such file or directory

该脚本实际上非常简单,来自“Bash Guide for Beginners”:

#!/bin/bash
# This script clears the terminal, displays a greeting and gives information
# about currently connected users.  The two example variables are set and displayed.
clear                           # clear terminal window
echo "The script starts now."
echo "Hi, $USER!"               # dollar sign is used to get content of variable
echo
echo "I will now fetch you a list of connected users:"
echo
w                               # show who is logged on and
echo                            # what they are doing
echo "I'm setting two variables now."
COLOUR="black"
VALUE="9"
echo "This is a string: $COLOUR"
echo "And this is a number: $VALUE"
echo
echo "I'm giving you back your prompt now."
echo

,实际上有“/ bin / bash”:

unknown_b8-8d-1b-3d-0b-3d:myscript liuren$ cd /bin
unknown_b8-8d-1b-3d-0b-3d:bin liuren$ ls
[       df      launchctl   pwd     tcsh
bash        domainname  link        rcp     test
cat     echo        ln      rm      unlink
chmod       ed      ls      rmdir       wait4path
cp      expr        mkdir       sh      zsh
csh     hostname    mv      sleep
date        kill        pax     stty
dd      ksh     ps      sync
unknown_b8-8d-1b-3d-0b-3d:bin liuren$ 

使用其他方式运行它,它没有显示结果

unknown_b8-8d-1b-3d-0b-3d:myscript liuren$ source script1.sh
unknown_b8-8d-1b-3d-0b-3d:myscript liuren$ bash script1.sh
unknown_b8-8d-1b-3d-0b-3d:myscript liuren$ bash -x script1.sh

我猜它没用。我该如何解决这个问题?

PS。什么是“unknown_b8-8d-1b-3d-0b-3d”,是否可以将其更改为更有意义的内容?

1 个答案:

答案 0 :(得分:1)

我之前看到过shebang行有DOS风格的line endings(通常是在Windows PC上创建的时候)。

如果你cat -vet ./script1.sh,你可能会看到:

#!/bin/bash^M$
[...]

删除这些回车,您将被设置。

一种方法是:

tr -d '\r' <  ./script1.sh > ./script2.sh

...这将创建一个没有回车符的新文件(./script2.sh)。

如果你使./script2.sh可执行文件(chmod +x ./script2.sh),你应该能够运行它(无需更新${PATH},通常一个糟糕的计划是将当前目录放在你的${PATH}”,

要查找提示的所有元素(unknown_b8-8d-1b-3d-0b-3d:myscript liuren$),,请使用:

echo $PS1

这将包含\w等字符,例如,它们会扩展到当前工作目录。

您可以在Bash Reference Manual

中查看这些代码的完整列表

快乐的脚本!