简体   繁体   English

用* shell bash读取文件名

[英]Read filename with * shell bash

I'am new in Linux and I want to write a bash script that can read in a file name of a directory that starts with LED + some numbers.(Ex.: LED5.5.002) 我是Linux的新手,我想编写一个bash脚本,该脚本可以读取以LED +一些数字开头的目录的文件名。(例如:LED5.5.002)

In that directory there is only one file that will starts with LED. 在该目录中,只有一个文件以LED开头。 The problem is that this file will every time be updated, so the next time it will be for example LED6.5.012 and counting. 问题是该文件每次都会更新,因此下一次它将是例如LED6.5.012并正在计数。

I searched and tried a little bit and came to this solution: 我搜索并尝试了一下,然后得出以下解决方案:

export fspec=/home/led/LED*
LedV=`basename $fspec`
echo $LedV

If I give in those commands one by one in my terminal it works fine, LedV= LED5.5.002 but if i run it in a bash scripts it gives the result: LedV = LED* 如果我在终端中一个接一个地输入这些命令,则它工作正常,LedV = LED5.5.002,但是如果我在bash脚本中运行它,则结果如下:LedV = LED *

I search after another solution: 我在寻找另一种解决方案:

a=/home/led/LED* LedV=$(basename $a) echo $LedV a=/home/led/LED* LedV=$(basename $a) echo $LedV

but here again the same, if i give it in one by one it's ok but in a script: LedV = LED*. 但是这里还是一样,如果我一一给出,可以,但是在脚本中:LedV = LED *。

It's probably something small but because of my lack of knowledge over Linux I cannot find it. 它可能很小,但是由于我对Linux缺乏了解,所以找不到它。 So can someone tell what is wrong? 那么有人能说出什么问题吗?

Thanks! 谢谢! Jan 一月

Shell expansions don't happen on scalar assignments, so in Shell扩展不会在标量分配中发生,因此在

varname=foo*

the expansion of "$varname" will literally be "foo*" . "$varname"的扩展名实际上是"foo*" It's more confusing when you consider that echo $varname (or in your case basename $varname ; either way without the double quotes) will cause the expansion itself to be treated as a glob, so you may well think the variable contains all those filenames. 当您考虑将echo $varname (或者在您的情况下为basename $varname ;不带双引号的任何一种方式)将扩展本身视为glob时,这将更加令人困惑,因此您很可能会认为变量包含所有这些文件名。

Array expansions are another story. 数组扩展是另一回事。 You might just want 你可能只想

fspec=( /path/LED* )
echo "${fspec[0]##*/}" # A parameter expansion to strip off the dirname

That will work fine for bash. 这对于bash来说很好用。 Since POSIX sh doesn't have arrays like this, I like to give an alternative approach: 由于POSIX sh没有这样的数组,因此我想提供一种替代方法:

for fspec in /path/LED*; do
    break
done
echo "${fspec##*/}"
pwd
/usr/local/src

ls -1 /usr/local/src/mysql*
    /usr/local/src/mysql-cluster-gpl-7.3.4-linux-glibc2.5-x86_64.tar.gz
    /usr/local/src/mysql-dump_test_all_dbs.sql

if you only have 1 file, you will only get 1 result 如果只有1个文件,则只会得到1个结果

MyFile=`ls -1 /home/led/LED*`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM