繁体   English   中英

我无法运行我的bash脚本

[英]I can't get my bash script to run

这是我以前无法运行的脚本,但是我希望有人可以帮助我确定问题所在。 我是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

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

也可以看看chmod手册(man chmod)。 大多数时候,我只是使用chmod +x ./my_file赋予执行权限

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM