[英]check if passed arguments to bash script is same as a filename
I want to check if the argument passed while executing the script matches the prefix of a filename in my directory.我想检查执行脚本时传递的参数是否与我目录中文件名的前缀匹配。 I m facing
binary operator expected
error with my code.我的代码面临
binary operator expected
的错误。 Does any body have any alternative approach ?有没有任何机构有任何替代方法?
./test.sh abc
fucn_1(){
if [ -e $file_name* ] ; then
func_2
else
echo "file not found"
exit
fi
}
if [ $1 == abc ];
then
file_name=`echo $1`
fucn_1
elif [ $1 == xyz ];
then
file_name=`echo $1`
fucn_1
while running I m passing abc as the argument such that then script can then check if the filenames starting with 'abc' is present or not in the directory.在运行时,我将 abc 作为参数传递,这样脚本就可以检查目录中是否存在以 'abc' 开头的文件名。 the dir has files :-
目录有文件: -
abc_1234.txt
abc_2345.txt
The glob $file_name*
expands to a list of files. glob
$file_name*
扩展为文件列表。 You ran [ -e abc_1234.txt abc_2345.txt ]
which gives an error, since [ -e
expects only one file, not two.您运行了
[ -e abc_1234.txt abc_2345.txt ]
,它给出了一个错误,因为[ -e
只需要一个文件,而不是两个。
Try something like ...尝试类似...
#! /usr/bin/env bash
shopt -s nullglob
has_args() { (( "$#" > 0 )); }
if has_args "$1"*; then
echo "$1 is a prefix of some file or dir"
else
echo "$1 is not a prefix of any file or dir"
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.