我无法让我的bash脚本运行

时间:2015-06-19 03:12:48

标签: linux bash

这是我以前不会运行的脚本,但我希望有人可以帮我弄清问题是什么。我是unix的新手

#!/bin/bash

# cat copyit

# copies files


numofargs=$#
listoffiles=
listofcopy=


# Capture all of the arguments passed to the command, store all of the                     arguments, except
# for the last (the destination)


while [ "$#" -gt 1 ]
do
listoffiles="$listoffiles $1"
shift
done

destination="$1"


# If there are less than two arguments that are entered, or if there are          more than two
# arguments, and the last argument is not a valid directory, then display an
# error message


if [ "$numofargs" -lt 2 -o "$numofargs" -gt 2 -a ! -d "$destination" ]
then
echo "Usage: copyit sourcefile destinationfile"
echo" copyit sourcefile(s) directory"
exit 1
fi


# look at each sourcefile


for fromfile in $listoffiles
do


# see if destination file is a directory


if [ -d "$destination" ]
then
destfile="$destination/`basename $fromfile`"
else
destfile="$destination"
fi


# Add the file to the copy list if the file does not already exist, or it
# the user
# says that the file can be overwritten



if [ -f "$destfile" ]
then 
echo "$destfile already exist; overwrite it? (yes/no)? \c"
read ans

if [ "$ans" = yes ]
then
listofcopy="$listofcopy $fromfile"
fi

else
listofcopy="$listofcopy $fromfile"
fi
done


# If there is something to copy - copy it


if [ -n "$listofcopy" ]
then
mv $listofcopy $destination
fi

这就是我得到的内容,虽然我调用了它,但脚本似乎没有执行所有操作。我希望有人可以帮助我

[taniamack@localhost ~]$ chmod 555 tryto.txt
[taniamack@localhost ~]$ tryto.txt
bash: tryto.txt: command not found...
[taniamack@localhost ~]$ ./tryto.txt
./tryto.txt: line 7: $'\r': command not found
./tryto.txt: line 11: $'\r': command not found
./tryto.txt: line 16: $'\r': command not found
./tryto.txt: line 43: syntax error near unexpected token `$'do\r''
'/tryto.txt: line 43: `do

2 个答案:

答案 0 :(得分:2)

您的文件看起来包含Windows新行格式:" \ r \ n"。在Unix上,新行只是" \ n"。您可以使用dos2unix(apt-get install dos2unix)来转换文件。

另请参阅chmod手册(man chmod)。 大多数时候我只使用chmod +x ./my_file来赋予执行权

答案 1 :(得分:0)

我看到一些问题。首先,555模式意味着没有人可以写入该文件。你可能想要chmod 755。其次,您需要将当前目录添加到$PATH变量中。在Windows中,您还有%PATH%,但默认情况下,当前目录.始终位于%PATH%,但在Unix中,由于安全问题,强烈建议不要添加当前目录。标准是将您的脚本放在$HOME/bin目录下,并将该目录作为$PATH中的最后一个条目。

首先:正确缩进。当您输入循环或if语句时,将行缩进四个字符(标准符号)。它使您更容易阅读您的程序。

另一个问题是你的行结尾。看起来有些行有一行Windows结尾,而大多数行有一行Unix / Linux / Mac行结尾。 Windows以两个字符结束每一行 - 回车换行,而Unix / Linux / Mac只用 Linefeed 结束每一行。 \r用于表示回车符。使用vimgedit等程序编辑器。一个好的程序编辑器将确保您的行结束一致和正确。