如果传递的参数是文件或目录,如何检入 bash 脚本?

use*_*607 5 bash scripts

我必须在 Ubuntu 中编写一个简单的 bash 脚本,它允许我向它传递一些参数,我想检查这些可以包含空格的参数是否是文件或目录。我怎样才能做到这一点?

Dan*_*ela 8

示例脚本:

#!/bin/bash
# This is a simple demo script
# It takes 3 parameters and checks if they are files or directories

echo "Welcome to my script"

if [[ -f "$1" || -d "$1" ]]
then
    echo "The First argument is a file or directory"
fi

if [[ -f "$2" || -d "$2" ]]
then
    echo "The second argument is a file or directory"
fi

if [[ -f "$3" || -d "$3" ]]
then
    echo "The third argument is a file or directory"
fi

echo "Bye!"
Run Code Online (Sandbox Code Playgroud)

示例场景

我保存的脚本~/script.sh,做chmod +x script.sh

karimov-danil@Karimov-Danil:~$ ./script.sh "??? ????" “???????????????” “讲话”
欢迎来到我的剧本
第一个参数是文件或目录
第二个参数是文件或目录
第三个参数是文件或目录
再见!

注意:您应该在双引号内传递参数。