【问题标题】:Unix - Shell script to find a file from any directory and move itUnix - 从任何目录中查找文件并移动的 Shell 脚本
【发布时间】:2014-10-26 19:47:24
【问题描述】:

我目前正在学习一本练习册,我必须创建一个 shell 脚本,它可以从任何目录中找到一个文件并将其移动。

虽然我遇到了困难,因为文件可能在任何目录中(所以我没有找到它的路径)。我已经使用了带有 -print 标志的 find 选项,那么下一步使用 mv 命令移动它是什么?

到目前为止,我的代码读取了一个变量,检测文件是否已被输入,是文件还是目录,或者它是否存在。

上面提到的下一个阶段是找到文件,然后将其移动到“测试”文件中。

如果有人有任何建议,将不胜感激。

#!/bin/bash

bin="deleted"

if [ !  -e bin ] ; then
    mkdir $bin
fi

file=$1

#error to display that no file has been entered
if [[ ! $file ]]; then
    echo "no file has been entered"
fi

#file does not exist, display error message
if [[ !  -f $file ]]; then
    echo "$file does not exsist!"
fi

#check to see if the input is a directory
if [[ -d $file ]]; then
    echo "$file is a directory!"

if [[ -e $file ]]; then *** move to test folder
****This is where I am having the problems

【问题讨论】:

    标签: shell unix


    【解决方案1】:

    find / -type f -name FILENAME | xargs -I foobar echo mv foobar /tmp(删除echo 以使命令真正起作用.. 我把它放在那里只是为了避免意外移动文件只是为了尝试命令)

    注意-I foobar 表示mv foobar /tmp 中的foobar 字符串替换为找到的文件的完整路径。

    例如,试试:find / -type f -name FILENAME | xargs -I foobar foobar is a cool file

    【讨论】:

    • 所以我的最终 if 语句 s/be: if [[ -e $file ]];然后找到 / -name 文件名 | xargs mv 测试?
    • 也许您还应该添加一个选项,例如 -not -wholename '/tmp/*'/path/to/test_dir/*
    • @user2141414 应该是:find / -name FILENAME | xargs -I foobar mv foobar /tmp ...小心!
    • @konsolebox 是的,我添加了echo,所以它实际上并没有进行移动
    • @user2141414 我在find 中添加了-type f 选项,以便它只对实际文件进行操作,而不对目录或符号链接进行操作。详情请见man find
    猜你喜欢
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 2015-11-11
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多