我正在尝试在Bourne shell中编写一个脚本来执行以下操作:
我对Bourne shell的使用很少,所以这就是我目前所拥有的。任何指针或提示将不胜感激,谢谢!
#!/bin/sh
#Scriptname: Trash Utility
source_dir=~/p6_tmp
target_dir=~/trash
echo "Please enter the filename you wish to trash:"
read filename
if [ -f $source_dir $filename]
then mv "$filename" "$target_dir"
else
echo "$filename does not exist"
fi
答案 0 :(得分:0)
您无法使用~
在$HOME
脚本中引用sh
。切换到$HOME
(或将shebang更改为支持此功能的shell,例如#!/bin/bash
)。
要引用目录中的文件,请使用斜杠连接它们:
if [ -f "$source_dir/$filename" ]
还要注意终止]
令牌之前所需的空格。
要实际移动您测试的文件,请对mv
的源参数使用相同的表达式:
mv "$source_dir/$filename" "$target_dir"
作为一般设计,采用命令行参数的脚本比交互式提示更容易集成到未来的脚本中。大多数现代shell提供文件名完成和历史机制,因此非交互式脚本也更容易使用(您几乎不需要手动转录文件名)。
答案 1 :(得分:0)
Bash解决方案:
#!/bin/bash
source_dir="~/p6_tmp"
target_dir="~/trash"
echo "Please enter the filename you wish to trash:"
read filename
if [ -f ${source_dir}/${filename} ]
then
if [ -f ${target_dir}/${filename} ]
then
mv "${source_dir}/${filename}" "${target_dir}/${filename}_bak"
else
mv "${source_dir}/${filename}" "$target_dir"
fi
else
echo "The file ${source_dir}/${filename} does not exist"
fi
答案 2 :(得分:0)
这是完成的脚本。再次感谢所有帮助过的人!
#!/bin/sh
#Scriptname: Trash Utility
#Description: This script will allow the user to enter a filename they wish to send to the trash folder.
source_dir=~/p6_tmp
target_dir=~/trash
echo "Please enter the file you wish to trash:"
read filename
if [ -f "$source_dir/$filename" ]
then
if [ -f "$target_dir/$filename" ]
then mv "$source_dir/$filename" "$target_dir/$(basename "$filename")_bak"
date "+%Y-%m-%d %T - Trash renamed ~/$(basename "$source_dir")/$filename to ~/$(basename "/$target_dir")/$(basename "$filename")_bak" >> .trashlog
else mv "$source_dir/$filename" "$target_dir"
date "+%Y-%m-%d %T - Trash moved ~/$(basename "/$source_dir")/$filename to ~/$(basename "/$target_dir")/$filename" >> .trashlog
fi
else
date "+%Y-%m-%d %T - Trash of ~/$(basename "/$source_dir")/$filename does not exist" >> .trashlog
fi