简体   繁体   中英

linux shell get name of file

I am writting shell script.

I have following files:

2012-03-08_16-37-41
2012-03-08_16-37-43
2012-03-08_16-37-46
2012-03-08_16-37-55

Simple script:

#!/bin/bash
FILENAME= ????
echo $FILENAME

And FILENAME value should be 2012-03-08_16-37-55 (last element of sorted file name list). Also, begin of file name should be 2012 .

How could I solve this problem?

FILENAME=$(ls -r 2012* | head -n 1)

Don't parse ls output. Instead, use find:

#!/bin/sh

find . -name 2012* | sort | tail -1

To assign the result to a variable:

#!/bin/sh

filename=$(find . -name 2012* | sort | tail -1)

This also gives you access to all of the many options find has , including (not)following symlinks, recursion, only returning files (not directories), checking timestamps and so on.

You can use either the ls command to get files, or just use "file globbing" to expand wildcards.

#!/bin/sh

for filename in 2012*; do
  echo "File (by globbing) is $filename"
done

ls 2012* | while read filename; do
  echo "File (via ls) is $filename"
done

To get the last one, the easiest way may be to sort the ls output:

filename=`ls -r 2012* | head -1`

But you can also just tail the glob, if you want to be messy.

for filename in 2012*; do
  echo "File (by globbing) is $filename"
done | tail -1
f=""; 
for f in 2012* ; 
do
  # haha - don't do anything. 
  dummy=42
done; 
echo "now do something with $f"

Without using any external commands: set 2012*; eval FILE=\\$$# set 2012*; eval FILE=\\$$# . This is a perfectly safe use of eval .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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