我编写了这些代码行来将用户提供的文件复制到目录中......但是条件部分不断引发错误......
以下是代码:
echo Enter filename to copy:
read files
echo
echo Enter Directory to copy files to:
read dir
echo
echo copying file $files to $dir directory
#check if file exists
if [ ! -e "$files" ] then
echo file does not exist
exit 0
else
if [ ! -d "$dir" ]; then #check if dir exists
mkdir ~$dir
echo ~$dir
cp $files $dir
ls $dir
fi
fi
预期行为:应将提供为argv的文件复制到提供的目录,如果该目录不存在,则应创建该文件。如果该文件不存在,则退出脚本,并显示该文件不存在的消息。
实际行为:syntax error near unexpected token 'else'
答案 0 :(得分:0)
您在第一个;
声明中遗漏了if
。它应该是:
if [ ! -e "$files" ]; then
答案 1 :(得分:0)
除了if语句中的语法错误外,如果传递多个文件,脚本将失败。一种可能的解决方案是将脚本重写为:
#!/usr/bin/env bash
echo Enter filename to copy:
read files
echo
echo Enter Directory to copy files to:
read dir
echo
echo copying file\(s\) $files to $dir directory
#check if file exists
for file in $files; do
if [ ! -e "$file" ]; then
echo file does not exist
exit 0
else
if [ ! -d "$dir" ]; then #check if dir exists
mkdir $dir
echo $dir
fi
cp "$file" "$dir"
fi
done
ls $dir
示例电话:
./scriptname *txt
这会将所有文本文件复制到指定的目录中。
答案 2 :(得分:0)
#!/bin/bash
echo Enter filename to copy:
read files
echo
echo Enter Directory to copy files to:
read dir
echo
echo copying file $files to $dir directory
#check if file exists
if [ ! -e $files ]; then #Missing ; and remove ""
echo file does not exist
exit 0
elif [ ! -d $dir ]; then #check if dir exists
mkdir -p ~$dir #-p for recursive folder path
echo ~$dir
fi
cp $files $dir #can mention -vf to force copy and verbose
ls $dir