linux - 如何在 Bash 中使用 '*' 通配符检查参数是否相等?

标签 linux bash shell glob

<分区>

我是 bash 脚本的新手,我正在编写一个脚本来自动使新创建的 .sh 文件可执行。因此,我想检查 .sh 前面是否有提供的唯一参数,以确保文件名有效。

但是,当我运行 ./createExecutableScript.sh asd.sh 时,出现了 [: too many arguments 错误。

一开始我以为是$1没有包裹在"里导致的错误,所以加了"进去。

我也提到了这个问题 ( Linux Shell Script - String Comparison with wildcards ) 并在 " 之外添加了 *

#!/bin/bash

if [ "$#" -eq 1 ] && [ "$1" == *".sh" ]
then
    echo "Creating file with name: $1"
else
    echo "Invalid or missing filename!"
fi

最佳答案

Linux Shell Script - String Comparison with wildcards中的答案是正确的,你需要有这样的双括号:

#!/bin/bash

if [ "$#" -eq 1 ] && [[ "$1" == *".sh" ]]
then
    echo "Creating file with name: $1"
else
    echo "Invalid or missing filename!"
fi

关于linux - 如何在 Bash 中使用 '*' 通配符检查参数是否相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56721973/

相关文章:

linux - 如何使 libusb 库对另一个程序可见?

linux - 使用 sed 在行范围之间查找和替换文件中的文本

linux - 在适用于 Linux 的 Windows 子系统上的 Ubuntu 上使用 INT 0x80 汇编编译的可执行文件不产生输出

ios - 我有两个 Xcode 项目,找出其中两个文件不同的最简单方法是什么?

linux - 如何用字符串和随机生成的数字替换文件中的 header 值?

linux - tar 命令不生成 .tar.gz 文件

Python/sed 获取文件中模式第一次出现和最后一次出现之间的数据

linux - 为什么在 $() 中使用管道时 bash 会执行我的脚本的 2 个实例

linux - 如何在 shell 脚本中进行比较?

运行简单 shell 脚本的 Python 文本菜单