Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Subshell behaviour of ls

I am wondering why I do not get se same output from:

ls -1 -tF | head -n 1

and

echo $(ls -1 -tF | head -n 1)

I tried to get the last modified file, but using it inside a sub shell sometimes I get more than one file as result?

Why that and how to avoid?

like image 291
Martin T. Avatar asked Jan 28 '26 04:01

Martin T.


1 Answers

The problem arises because you are using an unquoted subshell and -F flag for ls outputs shell special characters appended to filenames.

-F, --classify
append indicator (one of */=>@|) to entries

Executable files are appended with *.

When you run

echo $(ls -1 -tF | head -n 1)

then

$(ls -1 -tF | head -n 1)

will return a filename, and if it happens to be an executable and also be the prefix to another file, then it will return both.

For example if you have

test.sh
test.sh.backup

then it will return

test.sh*

which when echoed expands to

test.sh test.sh.backup

Quoting the subshell prevents this expansion

echo "$(ls -1 -tF | head -n 1)"

returns

test.sh*
like image 148
123 Avatar answered Jan 29 '26 18:01

123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!