gpt4 book ai didi

linux - 接受参数和条件 Bash

转载 作者:太空宇宙 更新时间:2023-11-04 05:15:31 25 4
gpt4 key购买 nike

我正在尝试制作一个采用单个命令行参数的脚本。然后它查看参数,如果它是目录名称,它只会打印该目录存在。如果它是文件名,则打印出该文件存在。否则,它会尝试创建具有此名称的目录并测试它是否成功并在标准输出上报告此情况。

我的代码是:

while read argument; do
if [ $argument -d ]; then
echo "Directory exists"
elif [ $argument -e ]
echo "File exists"
else
mkdir $argument
if [ $argument -d]; then
echo "Directory was created"
else
echo "Error while creating the directory"
fi
fi
done

然后我运行代码./file_name.sh argument。如果我像这样运行代码,我会在第 8 行收到一个错误,即“else”。虽然这里可能没有必要,但这是我想到的第一个选择如何从命令行接受参数。

最佳答案

正如您所提到的,您需要单个命令行参数,因此不需要循环

#!/bin/bash
if [[ -z "$1" ]]; then
echo "Help : You have to pass one argument"
exit 0
fi
if [[ -d "$1" ]]; then
echo "Directory exists"
elif [[ -f "$1" ]]; then
echo "File exists"
else
mkdir "$1"
if [ -d "$1" ]; then
echo "Directory was created"
else
echo "Error while creating the directory"
fi
fi

关于linux - 接受参数和条件 Bash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49964875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com