如何解析 Bash 中函数输入的元字符?

如何解析 Bash 中函数输入的元字符?

我在 bash 中编写了一个函数,该函数以 * 作为输入,因此应该列出该特定目录中的所有文件。但没有。这是我写的:

    # a function that mass deletes files in a directory but asks before deleting
    yrm()
    {
    echo "The following files are going to be deleted:"
    ls "${1}"
    read -e -n 1 -p "Do you want to delete these files? Y/n" ANSWER
    ${ANSWER:="n"} 2> /dev/null 

    if [ $ANSWER == "Y" ]
        then
            rm $1
        else
            echo "aborted by user"

    fi

}

但是我使用这些文件进行了测试:

l1zard@Marvin:~/.rclocal/test$ ls *
test1.txt  test2.txt  test3.txt  test5.txt  test7.txt  test8.txt  test9.txt  testm7m767.txt

我从我的函数中得到这个输出:

l1zard@Marvin:~/.rclocal/test$ yrm *
The following files are going to be deleted:
test1.txt
Do you want to delete these files? Y/nn
aborted by user

我该如何修复它以便它能按预期列出文件?

答案1

尝试类似:

ls "$@"
read ...
if [ "${ANSWER:=n}" = Y ]
then
  rm "$@"

但是您还需要测试文件是否指定以及它们是否存在。

答案2

该函数现在看起来像这样,并且由于 Scrutinizer 的作用,它确实可以工作:

# a function that mass deletes files in a directory but asks before realy delting those
yrm()
{
echo "The following files are going to be deleted:"
ls "$@"
rm -rI "$@"
}

相关内容