问题描述
这可能是一个shell脚本编程很简单的事情,但我pretty新的给它。我试图在一个shell脚本来执行下面的命令,并将输出保存到一个变量
This might be a very simple thing for a shell scripting programmer but am pretty new to it. I was trying to execute the below command in a shell script and save the output into a variable
inputfile=$(ls -ltr *.{PDF,pdf} | head -1 | awk '{print $9}')
当我从终端火,但是当通过shell脚本(SH)执行失败,命令工作正常。这是为什么命令失败,这是否意味着shell脚本不支持命令还是我做错了?另外我怎么知道,如果一个命令将在外壳或不工作?
The command works fine when I fire it from terminal but fails when executed through a shell script (sh). Why is that the command fails, does it mean that shell script doesn't support the command or am I doing it wrong? Also how do I know if a command will work in shell or not?
只是为了给你我的要求一瞥,我试图从特定目录中获取最旧的文件(我也希望确保大写和小写扩展处理)。是否有任何其他方式做到这一点?
Just to give you a glimpse of my requirement, I was trying to get the oldest file from a particular directory (I also want to make sure upper case and lower case extensions are handled). Is there any other way to do this ?
推荐答案
上面的命令将正常工作,只有当两个 *。PDF
和 * .PDF
文件在你当前的目录。
如果您想在一个目录,只有那些你应该考虑使用例如一个执行它。
The above command will work correctly only if BOTH *.pdf
and *.PDF
files are in the directory you are currently.If you would like to execute it in a directory with only one of those you should consider using e.g.:
inputfiles=$(find . -maxdepth 1 -type f \( -name "*.pdf" -or -name "*.PDF" \) | xargs ls -1tr | head -1 )
的注意的:上述命令不带新线,或者找到的文件一长串文件的工作。
NOTE: The above command doesn't work with files with new lines, or with long list of found files.
这篇关于在UNIX上市文件,并在一个变量保存输出(最早的文件读取特定扩展名)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!