When i try the below code am getting all files whose filename starts with E
#!/bin/bash
data=$(ls -trh E*)
for entry in ${data}
do
echo ${entry}
done
But if i try the below code , which get the wildcard from argument , i am getting only the first filename
#!/bin/bash
data=$(ls -trh $1)
for entry in ${data}
do
echo ${entry}
done
Can anyone help me to solve this ..
When i gave quotes like this myscript.sh 'E*' it worked fine , is there any way to do this without giving quotes ?
Your shell will interpret wildcard characters before passing then to your process. For example:
script.sh
#!/bin/bash
echo $1 $2 $3
Running the above with a wildcard:
> ./script.sh E*
Eva Eve Evolve
If you want to pass an argument without shell interpreting it first, you will have to quote it:
> ./script.sh 'E*'
E*
find
:What you're actually trying to do is get a list of all files and folders in a given directory, in reverse modification time order (oldest first). The output of ls
is notoriously painful to parse. It is preferable to use the powerful and flexible find
command instead.
This is a one liner:
> find ./ -maxdepth 1 -printf "%A@ %f\0" | sort -z -n | while read -d '' date line; do echo "$line"; done
Which is probably cryptic, but makes sense once explained.
find ./ -maxdepth 1
-printf "%A@
%f\0"
sort -z -n
while read -d '' date line
echo "$line"
For example, in my directory:
> ls -l
total 4296
drwxr-xr-x 2 bfer cvs 4096 2012-03-05 15:49 colortry
drwxr-xr-x 3 bfer cvs 4096 2012-03-27 15:05 githug
drwxr-xr-x 3 bfer cvs 4096 2012-03-12 17:18 hooks-bare
drwxr-xr-x 3 bfer cvs 4096 2012-03-28 12:38 java
-rw-r--r-- 1 bfer cvs 4025413 2012-03-27 12:53 mozdebug
drwxr-xr-x 2 bfer cvs 4096 2012-02-16 12:54 mustache_bug_demo
-rwxr-xr-x 1 bfer cvs 113 2012-03-30 12:20 try.sh
> find ./ -maxdepth 1 -printf "%A@ %f\0" | sort -z -n | while read -d '' date line; do echo "$line"; done
mozdebug
colortry
hooks-bare
mustache_bug_demo
githug
java
try.sh
./
If you don't want the ./
result, just take it out of your final set.
updated: With Sorpigal's suggestion to handle filenames with newlines.
This is the same with things like parenthesis and ampersands. For example, the following curl commands will not work as expected:
> curl example.com/site?q=hello&name=bob
> echo 23/(7/98) | bc
As the ampersand and parentheses will be interpreted by the shell before they are passed to the process as arguments.
For this to work correctly, you will have to quote the args:
> curl "example.com/site?q=hello&name=bob"
> echo "23/(7/98)" | bc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With